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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
Messages.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/Messages.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.ResourceBundle.Control;
import org.apache.commons.io.IOUtils;
/**
* Message bundle handler.
*
* @author Aleś Bułojčyk <alex73mail@gmail.com>
*/
public class Messages {
static ResourceBundle messages;
static {
messages = ResourceBundle.getBundle("org.alex73.skarynka.scan.messages", new UTF8Control());
}
public static String getString(String key) {
return messages.getString(key);
}
public static String getString(String key, Object... param) {
String pattern = messages.getString(key);
return MessageFormat.format(pattern, param);
}
public static String getFile(String name) {
Locale loc1 = Locale.getDefault();
Locale loc2 = new Locale(loc1.getLanguage(), loc1.getCountry());
Locale loc3 = new Locale(loc1.getLanguage());
for (Locale loc : new Locale[] { loc1, loc2, loc3 }) {
URL r = Messages.class.getResource(name.replaceAll("(\\.[a-zA-Z0-9]+)$", "_" + loc + "$1"));
if (r != null) {
try {
return IOUtils.toString(r, "UTF-8");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
URL r = Messages.class.getResource(name);
if (r != null) {
try {
return IOUtils.toString(r, "UTF-8");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
return null;
}
public static class UTF8Control extends Control {
public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader,
boolean reload) throws IllegalAccessException, InstantiationException, IOException {
// The below is a copy of the default implementation.
String bundleName = toBundleName(baseName, locale);
String resourceName = toResourceName(bundleName, "properties");
ResourceBundle bundle = null;
InputStream stream = null;
if (reload) {
URL url = loader.getResource(resourceName);
if (url != null) {
URLConnection connection = url.openConnection();
if (connection != null) {
connection.setUseCaches(false);
stream = connection.getInputStream();
}
}
} else {
stream = loader.getResourceAsStream(resourceName);
}
if (stream != null) {
try {
// Only this line is changed to make it to read properties files as UTF-8.
bundle = new PropertyResourceBundle(new InputStreamReader(stream, "UTF-8"));
} finally {
stream.close();
}
}
return bundle;
}
}
}
| 4,192 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
IPagePreviewChanged.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/IPagePreviewChanged.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan;
import java.awt.Image;
/**
* Listener for page preview changed.
*
* @author Aleś Bułojčyk <alex73mail@gmail.com>
*/
public interface IPagePreviewChanged {
void show(Image image);
}
| 1,138 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
ITabController.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/ITabController.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan;
import java.awt.Component;
/**
* Interface for tab control.
*
* @author Aleś Bułojčyk <alex73mail@gmail.com>
*/
public interface ITabController {
void deactivate();
void activate();
void close();
String getTabName();
Component getTabComponent();
}
| 1,225 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
Scan2.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/Scan2.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import java.util.jar.Manifest;
import javax.swing.AbstractButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
import org.alex73.skarynka.scan.devices.Stub;
import org.alex73.skarynka.scan.hid.HIDScanController;
import org.alex73.skarynka.scan.process.ProcessDaemon;
import org.alex73.skarynka.scan.ui.MainFrame;
import org.alex73.skarynka.scan.ui.ToolsPedalController;
import org.alex73.skarynka.scan.ui.add.AddController;
import org.alex73.skarynka.scan.ui.book.BooksController;
import org.alex73.skarynka.scan.ui.book.PanelEditController;
import org.alex73.skarynka.scan.ui.scan.ScanDialogController;
import org.alex73.skarynka.scan.wizards.camera_badpixels.CameraBadPixelsWizard;
import org.alex73.skarynka.scan.wizards.camera_focus.CameraFocusController;
import org.alex73.skarynka.scan.wizards.camera_init.CameraInitWizard;
import org.apache.log4j.PropertyConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Main class for execution.
*
* @author Aleś Bułojčyk <alex73mail@gmail.com>
*/
public class Scan2 {
private static Logger LOG = LoggerFactory.getLogger(Scan2.class);
public static void main(String[] args) {
try {
File lockFile = new File("scan.lock");
FileChannel lockChannel = new RandomAccessFile(lockFile, "rw").getChannel();
FileLock lock = lockChannel.tryLock();
if (lock == null) {
JOptionPane.showMessageDialog(null, Messages.getString("FRAME_ALREADY_RUNNING"),
Messages.getString("ERROR_TITLE"), JOptionPane.ERROR_MESSAGE);
return;
}
PropertyConfigurator.configure("log4j.properties");
String version = readVersion();
LOG.info("Skarynka start version " + version);
Context.load();
String locale_language = Context.getSettings().get("locale_language");
String locale_country = Context.getSettings().get("locale_country");
String locale_variant = Context.getSettings().get("locale_variant");
if (locale_language != null) {
if (locale_country != null) {
if (locale_variant != null) {
Locale.setDefault(new Locale(locale_language, locale_country, locale_variant));
} else {
Locale.setDefault(new Locale(locale_language, locale_country));
}
} else {
Locale.setDefault(new Locale(locale_language));
}
}
DataStorage.mainFrame = new MainFrame();
DataStorage.mainFrame.setSize(700, 500);
DataStorage.mainFrame
.setExtendedState(DataStorage.mainFrame.getExtendedState() | JFrame.MAXIMIZED_BOTH);
if (Context.getPermissions().ProcessingBooks || Context.getPermissions().ProcessingControls) {
DataStorage.daemon = new ProcessDaemon();
DataStorage.daemon.start();
} else {
DataStorage.mainFrame.cbProcess.setVisible(false);
}
setup();
DataStorage.addTab(new BooksController());
if (Context.getSettings().get("mousepedal-usbid") != null) {
DataStorage.hidScanDevice = new HIDScanController(Context.getSettings().get("mousepedal-usbid"),
Context.getSettings().get("mousepedal-usbInterfaceProtocol"));
DataStorage.hidScanDevice.start();
}
DataStorage.mainFrame.setTitle(Messages.getString("FRAME_TITLE", version));
DataStorage.mainFrame.setVisible(true);
} catch (Throwable ex) {
LOG.error("Error startup", ex);
JOptionPane.showMessageDialog(null, "Error: " + ex.getClass() + " / " + ex.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
}
}
static void setup() {
if (System.getProperty("STUB") != null) {
DataStorage.mainFrame.cameraMenu.setVisible(false);
DataStorage.device = new Stub("/data/tmp/scan/stub");
}
DataStorage.mainFrame.cameraBadPixels.setVisible(Context.getPermissions().CameraBadPixels);
DataStorage.mainFrame.cameraMenu.setVisible(Context.getPermissions().ShowDevices);
DataStorage.mainFrame.processScan.setVisible(Context.getPermissions().ShowDevices);
DataStorage.mainFrame.processAdd.setVisible(Context.getPermissions().ShowManualAdd);
DataStorage.mainFrame.addAllFiles.setVisible(Context.getPermissions().ShowManualAdd);
DataStorage.mainFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
DataStorage.finish();
}
});
if (DataStorage.daemon != null) {
DataStorage.mainFrame.cbProcess.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
DataStorage.daemon.setPaused(DataStorage.mainFrame.cbProcess.isSelected());
}
});
}
DataStorage.mainFrame.cameraInit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new CameraInitWizard().process();
}
});
DataStorage.mainFrame.cameraFocus.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
DataStorage.device.setPreviewPanels();
new CameraFocusController().show();
}
});
DataStorage.mainFrame.cameraBadPixels.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new CameraBadPixelsWizard().process();
}
});
DataStorage.mainFrame.cameraMenu.addMenuListener(new MenuListener() {
@Override
public void menuSelected(MenuEvent e) {
DataStorage.mainFrame.cameraFocus.setEnabled(DataStorage.device != null);
DataStorage.mainFrame.cameraBadPixels.setEnabled(DataStorage.device != null);
}
@Override
public void menuDeselected(MenuEvent e) {
}
@Override
public void menuCanceled(MenuEvent e) {
}
});
DataStorage.mainFrame.addAllFiles.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
AddController.addAll();
}
});
DataStorage.mainFrame.processScan.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ScanDialogController.show((PanelEditController) DataStorage.getActiveTab());
}
});
DataStorage.mainFrame.processAdd.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
AddController.add((PanelEditController) DataStorage.getActiveTab());
}
});
DataStorage.mainFrame.workMenu.addMenuListener(new MenuListener() {
@Override
public void menuSelected(MenuEvent e) {
boolean deviceReady = DataStorage.device != null && DataStorage.device.readyForScan();
DataStorage.mainFrame.processScan.setEnabled(deviceReady);
}
@Override
public void menuDeselected(MenuEvent e) {
}
@Override
public void menuCanceled(MenuEvent e) {
}
});
DataStorage.mainFrame.itemAll.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
DataStorage.view = DataStorage.SHOW_TYPE.ALL;
DataStorage.refreshBookPanels(false);
}
});
DataStorage.mainFrame.itemSeq.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
DataStorage.view = DataStorage.SHOW_TYPE.SEQ;
DataStorage.refreshBookPanels(false);
}
});
DataStorage.mainFrame.itemOdd.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
DataStorage.view = DataStorage.SHOW_TYPE.ODD;
DataStorage.refreshBookPanels(false);
}
});
DataStorage.mainFrame.itemEven.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
DataStorage.view = DataStorage.SHOW_TYPE.EVEN;
DataStorage.refreshBookPanels(false);
}
});
DataStorage.mainFrame.itemCropErr.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
DataStorage.view = DataStorage.SHOW_TYPE.CROP_ERRORS;
DataStorage.refreshBookPanels(false);
}
});
DataStorage.mainFrame.viewMenu.addMenuListener(new MenuListener() {
@Override
public void menuSelected(MenuEvent e) {
boolean bookOpened = true;// TODO DataStorage.book != null;
for (Enumeration<AbstractButton> en = DataStorage.mainFrame.viewButtonsGroup.getElements(); en
.hasMoreElements();) {
en.nextElement().setEnabled(bookOpened);
}
}
@Override
public void menuDeselected(MenuEvent e) {
}
@Override
public void menuCanceled(MenuEvent e) {
}
});
DataStorage.mainFrame.viewInc.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
DataStorage.previewMaxHeight = Math.round(DataStorage.previewMaxHeight * 1.1f);
DataStorage.previewMaxWidth = Math.round(DataStorage.previewMaxHeight * 0.7f);
DataStorage.refreshBookPanels(true);
}
});
DataStorage.mainFrame.viewDec.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
DataStorage.previewMaxHeight = Math.round(DataStorage.previewMaxHeight * 0.9f);
DataStorage.previewMaxWidth = Math.round(DataStorage.previewMaxHeight * 0.7f);
DataStorage.refreshBookPanels(true);
}
});
DataStorage.mainFrame.closeBook.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
DataStorage.closeTab(DataStorage.getActiveTab());
}
});
DataStorage.mainFrame.toolsPedal.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ToolsPedalController.show();
}
});
for (Map.Entry<String, String> en : Context.getPageTags().entrySet()) {
String label = Messages.getString("MENU_VIEW_TAG", en.getValue());
JRadioButtonMenuItem item = new JRadioButtonMenuItem(label);
item.setName(en.getKey());
DataStorage.mainFrame.viewButtonsGroup.add(item);
DataStorage.mainFrame.viewMenu.add(item);
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
DataStorage.view = DataStorage.SHOW_TYPE.TAG;
DataStorage.viewTag = ((JRadioButtonMenuItem) e.getSource()).getName();
DataStorage.refreshBookPanels(false);
}
});
}
DataStorage.mainFrame.tabs.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
int sel = DataStorage.mainFrame.tabs.getSelectedIndex();
if (sel < 0) {
return;
}
DataStorage.activateTab(sel);
}
});
}
public static String readVersion() throws Exception {
String className = Scan2.class.getSimpleName() + ".class";
String classPath = Scan2.class.getResource(className).toString();
if (!classPath.startsWith("jar")) {
// Class not from JAR
return "dev";
}
String manifestPath = classPath.substring(0, classPath.lastIndexOf("!") + 1)
+ "/META-INF/MANIFEST.MF";
Manifest manifest;
try (InputStream in = new URL(manifestPath).openStream()) {
manifest = new Manifest(in);
}
return manifest.getMainAttributes().getValue("Build");
}
}
| 14,759 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
DataStorage.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/DataStorage.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan;
import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import javax.swing.JOptionPane;
import org.alex73.skarynka.scan.devices.ISourceDevice;
import org.alex73.skarynka.scan.hid.HIDScanController;
import org.alex73.skarynka.scan.process.ProcessDaemon;
import org.alex73.skarynka.scan.ui.MainFrame;
import org.alex73.skarynka.scan.ui.book.PanelEditController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Storage for devices and some methods for UI control.
*
* @author Aleś Bułojčyk <alex73mail@gmail.com>
*/
public class DataStorage {
private static Logger LOG = LoggerFactory.getLogger(DataStorage.class);
public static final int INITIAL_PREVIEW_MAX_WIDTH = 70;
public static final int INITIAL_PREVIEW_MAX_HEIGHT = 100;
public enum SHOW_TYPE {
ALL, SEQ, CROP_ERRORS, ODD, EVEN, TAG
};
public static MainFrame mainFrame;
public static ISourceDevice device;
public static boolean focused;
public static int previewMaxWidth = INITIAL_PREVIEW_MAX_WIDTH;
public static int previewMaxHeight = INITIAL_PREVIEW_MAX_HEIGHT;
// public static Book2 book;
// public static PagePreviewer pagePreviewer;
private static int tabSelectedIndex = -1;
private static final List<ITabController> tabControllers = new ArrayList<>();
// public static PanelEditController panelEdit;
public static SHOW_TYPE view = SHOW_TYPE.ALL;
public static String viewTag;
public static ProcessDaemon daemon;
public static HIDScanController hidScanDevice;
public static synchronized PanelEditController getOpenBookController(String bookName) {
for (ITabController c : tabControllers) {
if (c instanceof PanelEditController) {
PanelEditController cc = (PanelEditController) c;
if (bookName.equals(cc.getBook().getName())) {
// already open
return cc;
}
}
}
return null;
}
public static synchronized void closeTab(ITabController tab) {
tab.deactivate();
tabControllers.remove(tab);
mainFrame.tabs.remove(tab.getTabComponent());
tab.close();
}
public static void addTab(ITabController tab) {
tabControllers.add(tab);
mainFrame.tabs.add(tab.getTabName(), tab.getTabComponent());
mainFrame.tabs.setSelectedIndex(tabControllers.size() - 1);
}
public synchronized static void activateTab(int tabIndex) {
if (tabSelectedIndex >= 0 && tabSelectedIndex < tabControllers.size()) {
tabControllers.get(tabSelectedIndex).deactivate();
}
tabSelectedIndex = tabIndex;
tabControllers.get(tabSelectedIndex).activate();
}
/**
* If book already open - just activate it.
*/
public static synchronized Book2 openBook(String bookName, boolean showUI) {
PanelEditController ce = getOpenBookController(bookName);
if (ce != null) {
if (showUI) {
ce.activate();
}
return ce.getBook();
}
try {
File bookDir = new File(Context.getBookDir(), bookName);
Book2 book = new Book2(bookDir);
if (!book.getErrors().isEmpty()) {
throw new Exception(book.getErrors().toString());
}
if (!showUI) {
return book;
}
LOG.info("Open book " + bookName);
if (device != null) {
device.setPreviewPanels();
}
PanelEditController c = new PanelEditController(book);
addTab(c);
return c.getBook();
} catch (Exception ex) {
LOG.error("Error open book '" + bookName + "'", ex);
JOptionPane.showMessageDialog(mainFrame,
Messages.getString("ERROR_BOOK_OPEN", bookName, ex.getMessage()),
Messages.getString("ERROR_TITLE"), JOptionPane.ERROR_MESSAGE);
return null;
}
}
public static synchronized void refreshBookPanels(boolean resetAllPreviews) {
for (ITabController c : tabControllers) {
if (c instanceof PanelEditController) {
PanelEditController cc = (PanelEditController) c;
if (resetAllPreviews) {
cc.resetAllPreviews();
}
cc.show();
}
}
}
public synchronized static ITabController getActiveTab() {
int sel = mainFrame.tabs.getSelectedIndex();
return sel < 0 ? null : tabControllers.get(sel);
}
public static synchronized void iterateByBooks(Set<String> bookNames, IBookIterator iterator) {
File[] ls = new File(Context.getBookDir()).listFiles(new FileFilter() {
public boolean accept(File pathname) {
return pathname.isDirectory() && new File(pathname, "book.properties").isFile();
}
});
if (ls == null) {
ls = new File[0];
}
Arrays.sort(ls);
try {
for (File f : ls) {
if (bookNames != null && !bookNames.contains(f.getName())) {
continue;
}
PanelEditController c = getOpenBookController(f.getName());
if (c != null) {
iterator.onBook(c.getBook());
} else {
Book2 b = new Book2(f);
iterator.onBook(b);
}
}
} catch (Exception ex) {
throw new RuntimeException(ex.getMessage(), ex);
}
}
public static void finish() {
for (ITabController c : tabControllers) {
c.close();
}
LOG.info("Skarynka shutdown");
if (hidScanDevice != null) {
hidScanDevice.finish();
}
if (daemon != null) {
daemon.finish();
try {
daemon.join();
} catch (Exception ex) {
}
}
mainFrame.dispose();
}
}
| 7,160 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
Book2.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/Book2.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan;
import java.awt.image.BufferedImage;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import org.alex73.skarynka.scan.process.PageFileInfo;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Book info representation. This info stored in the <book>/book.properties file.
*
* @author Aleś Bułojčyk <alex73mail@gmail.com>
*/
public class Book2 {
public static final String[] IMAGE_EXTENSIONS = new String[] { "tif", "tiff", "jpg", "jpeg", "png", "bmp" };
public static final Pattern RE_PAGE_IMAGE_FILE = Pattern.compile("([0-9]+[a-z]*)\\.(tif|tiff|jpg|jpeg|png|bmp)",
Pattern.CASE_INSENSITIVE);
public static final Pattern IMAGE_FILE = Pattern.compile(".+\\.(tif|tiff|jpg|jpeg|png|bmp)",
Pattern.CASE_INSENSITIVE);
private static Logger LOG = LoggerFactory.getLogger(Book2.class);
static final Pattern RE_BOOK = Pattern.compile("book.([a-zA-Z]+)=(.+)");
static final Pattern RE_PAGE = Pattern.compile("page.([0-9a-z]+).([a-zA-z]+)=(.+)");
public class PageInfo {
public String pageNumber;
public int imageSizeX, imageSizeY;
public int cropPosX = -1, cropPosY = -1;
public Set<String> tags = new TreeSet<>();
public int rotate;
public boolean mirrorHorizontal, mirrorVertical, inverted;
public String camera;
public String pageOriginalFileExt;
public PageInfo(String pageNumber) {
this.pageNumber = pageNumber;
}
}
private final File bookDir, bookFile;
public transient boolean local;
private transient String localFor;
public int scale = 100;
public int dpi = 300;
public int zoom;
public int cropSizeX = -1, cropSizeY = -1;
public int pageStep = 2;
private Map<String, PageInfo> pages = new HashMap<>();
private List<String> errors = new ArrayList<>();
public Book2(File bookDir) throws Exception {
this.bookDir = bookDir;
this.bookFile = new File(bookDir, "book.properties");
new File(bookDir, "preview").mkdirs();
File localFile = new File(bookDir, ".local");
if (bookFile.exists()) {
for (String line : FileUtils.readLines(bookFile, "UTF-8")) {
Matcher m;
if ((m = RE_PAGE.matcher(line)).matches()) {
String page = formatPageNumber(m.group(1));
String fieldName = m.group(2);
String value = m.group(3);
PageInfo pi = pages.get(page);
if (pi == null) {
pi = new PageInfo(page);
pages.put(pi.pageNumber, pi);
}
set(pi, fieldName, value, line);
} else if ((m = RE_BOOK.matcher(line)).matches()) {
String fieldName = m.group(1);
String value = m.group(2);
set(this, fieldName, value, line);
}
}
for(PageInfo pi:pages.values()) {
if (!new PageFileInfo(this, pi.pageNumber).getOriginalFile().exists()) {
throw new RuntimeException(
"Page " + pi.pageNumber + " file not found in the book " + bookDir.getName());
}
}
if (localFile.exists()) {
localFor = FileUtils.readFileToString(localFile, "UTF-8");
local = Context.thisHost.equals(localFor);
} else {
local = false;
}
} else {
FileUtils.writeStringToFile(localFile, Context.thisHost, "UTF-8");
local = true;
save();
}
}
private void set(Object obj, String fieldName, String value, String debug) {
try {
Field f = obj.getClass().getField(fieldName);
if (!Modifier.isPublic(f.getModifiers()) || Modifier.isStatic(f.getModifiers())
|| Modifier.isTransient(f.getModifiers())) {
errors.add("Field is not public for '" + debug + "'");
return;
}
if (f.getType() == int.class) {
f.setInt(obj, Integer.parseInt(value));
} else if (f.getType() == boolean.class) {
f.setBoolean(obj, Boolean.parseBoolean(value));
} else if (f.getType() == String.class) {
f.set(obj, value);
} else if (Set.class.isAssignableFrom(f.getType())) {
TreeSet<String> v = new TreeSet<>(Arrays.asList(value.split(";")));
f.set(obj, v);
} else {
errors.add("Unknown field class for set '" + debug + "'");
return;
}
} catch (NoSuchFieldException ex) {
errors.add("Unknown field for set '" + debug + "'");
} catch (IllegalAccessException ex) {
errors.add("Wrong field for set '" + debug + "'");
} catch (Exception ex) {
errors.add("Error set value to field for '" + debug + "'");
}
}
private void get(Object obj, String prefix, List<String> lines) throws Exception {
for (Field f : obj.getClass().getFields()) {
if (Modifier.isPublic(f.getModifiers()) && !Modifier.isStatic(f.getModifiers())
&& !Modifier.isTransient(f.getModifiers())) {
if (f.getType() == int.class) {
int v = f.getInt(obj);
if (v != -1) {
lines.add(prefix + f.getName() + "=" + v);
}
} else if (f.getType() == boolean.class) {
lines.add(prefix + f.getName() + "=" + f.getBoolean(obj));
} else if (f.getType() == String.class) {
String s = (String) f.get(obj);
if (s != null) {
lines.add(prefix + f.getName() + "=" + s);
}
} else if (Set.class.isAssignableFrom(f.getType())) {
Set<?> set = (Set<?>) f.get(obj);
StringBuilder t = new StringBuilder();
for (Object o : set) {
t.append(o.toString()).append(';');
}
if (t.length() > 0) {
t.setLength(t.length() - 1);
}
lines.add(prefix + f.getName() + "=" + t);
} else {
throw new RuntimeException("Unknown field class for get '" + f.getName() + "'");
}
}
}
}
public String getName() {
return bookDir.getName();
}
public File getBookDir() {
return bookDir;
}
public int getPagesCount() {
return pages.size();
}
public String getStatusText() {
try {
if (!errors.isEmpty()) {
return Messages.getString("BOOK_STATUS_ERROR_READING");
}
if (new File(bookDir, ".errors").exists()) {
return Messages.getString("BOOK_STATUS_ERROR_PROCESSING");
}
if (new File(bookDir, ".process").exists()) {
String text = FileUtils.readFileToString(new File(bookDir, ".process"), "UTF-8");
return Messages.getString("BOOK_STATUS_PROCESSING", text);
}
if (new File(bookDir, ".process.done").exists()) {
String text = FileUtils.readFileToString(new File(bookDir, ".process.done"), "UTF-8");
return Messages.getString("BOOK_STATUS_PROCESSED", text);
}
if (localFor != null) {
return Messages.getString("BOOK_STATUS_LOCAL", localFor);
}
return Messages.getString("BOOK_STATUS_WAITING");
} catch (Exception ex) {
return Messages.getString("BOOK_STATUS_ERROR_READING");
}
}
public synchronized boolean pageExist(String p) {
return pages.containsKey(formatPageNumber(p));
}
public synchronized List<String> listPages() {
List<String> result = new ArrayList<>(pages.keySet());
Collections.sort(result);
return result;
}
public synchronized PageInfo getPageInfo(String page) {
return pages.get(page);
}
public List<String> getErrors() {
return errors;
}
public synchronized void addPage(PageInfo pageInfo) {
String page = formatPageNumber(pageInfo.pageNumber);
pages.put(page, pageInfo);
}
public synchronized PageInfo removePage(String pageNumber) {
String page = formatPageNumber(pageNumber);
return pages.remove(page);
}
public BufferedImage getImage(String pageNumber) throws Exception {
File f = new PageFileInfo(this, pageNumber).getPreviewFile();
return ImageIO.read(f);
}
public synchronized void save() throws Exception {
LOG.info("Save book " + bookDir);
List<String> lines = new ArrayList<>();
get(this, "book.", lines);
for (Map.Entry<String, PageInfo> en : pages.entrySet()) {
String p = en.getKey();
PageInfo pi = en.getValue();
get(pi, "page." + p + ".", lines);
}
Collections.sort(lines);
File bookFileNew = new File(bookFile.getPath() + ".new");
File bookFileBak = new File(bookFile.getPath() + ".bak");
FileUtils.writeLines(bookFileNew, "UTF-8", lines, "\n");
if (bookFileBak.exists()) {
if (!bookFileBak.delete()) {
throw new Exception("Can't delete .bak file");
}
}
if (bookFile.exists()) {
if (!bookFile.renameTo(bookFileBak)) {
throw new Exception("Can't rename old file to .bak");
}
}
if (!bookFileNew.renameTo(bookFile)) {
throw new Exception("Can't rename new file to " + bookFile.getAbsolutePath());
}
}
static final Pattern RE_PAGE_NUMBER = Pattern.compile("([0-9]+)([a-z]{0,2})");
public static String formatPageNumber(String pageNumber) {
if (pageNumber == null) {
return "";
}
Matcher m = RE_PAGE_NUMBER.matcher(pageNumber);
if (m.matches()) {
String n = m.group(1);
n = "00000".substring(n.length()) + n + m.group(2);
return n;
} else {
return "";
}
}
public static String simplifyPageNumber(String pageNumber) {
if (pageNumber == null) {
return "";
}
return pageNumber.replaceAll("^0+([0-9])", "$1");
}
public static int comparePageNumbers(String p1, String p2) {
Matcher m = RE_PAGE_NUMBER.matcher(p1);
if (!m.matches()) {
return 0;
}
int n1 = Integer.parseInt(m.group(1));
String s1 = m.group(2);
m = RE_PAGE_NUMBER.matcher(p2);
if (!m.matches()) {
return 0;
}
int n2 = Integer.parseInt(m.group(1));
String s2 = m.group(2);
if (n1 != n2) {
return n1 - n2;
}
return s1.compareTo(s2);
}
public static String incPage(String pageNumber, int incCount) {
if (Math.abs(incCount) > 4) {
throw new IllegalArgumentException("Wrong inc: " + incCount);
}
Matcher m = RE_PAGE_NUMBER.matcher(pageNumber);
if (!m.matches()) {
return "";
}
int n = Integer.parseInt(m.group(1));
String idx = m.group(2);
String r;
switch (idx.length()) {
case 0:
r = Integer.toString(n + incCount);
break;
case 1:
int i = idx.charAt(0);
i += incCount;
if (i >= 'a' && i <= 'z') {
r = n + "" + ((char) i);
} else {
r = "";
}
break;
case 2:
int i1 = idx.charAt(0);
int i2 = idx.charAt(1);
i2 += incCount;
if (i2 > 'z') {
i1++;
i2 = i2 - 'z' + 'a' - 1;
} else if (i2 < 'a') {
i1--;
i2 = i2 + 'z' - 'a' + 1;
}
if (i1 >= 'a' && i1 <= 'z' && i2 >= 'a' && i2 <= 'z') {
r = n + "" + ((char) i1) + ((char) i2);
} else {
r = "";
}
break;
default:
throw new RuntimeException("Too many letters in page number");
}
return formatPageNumber(r);
}
public static String incPagePos(String pageNumber, boolean letter, int count) {
if (Math.abs(count) > 4) {
throw new IllegalArgumentException("Wrong inc: " + count);
}
Matcher m = RE_PAGE_NUMBER.matcher(pageNumber);
if (!m.matches()) {
return "";
}
String result;
int n = Integer.parseInt(m.group(1));
String idx = m.group(2);
if (letter) {
if (idx.isEmpty()) {
result = null;
} else {
result = incPage(pageNumber, count);
}
} else {
n += count;
result = n + idx;
}
return formatPageNumber(result);
}
}
| 14,709 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
PagePreviewer.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/PagePreviewer.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.alex73.skarynka.scan.process.PageFileInfo;
/**
* Page preview handler.
*
* @author Aleś Bułojčyk <alex73mail@gmail.com>
*/
public class PagePreviewer {
private final Book2 book;
private Map<String, BufferedImage> cache = new HashMap<>();
private Map<String, IPagePreviewChanged> listeners = new HashMap<>();
private ExecutorService queue = Executors.newFixedThreadPool(1);
public PagePreviewer(Book2 book) {
this.book = book;
}
public void finish() {
queue.shutdownNow();
}
public void updatePreview(String pageNumber) {
String page = Book2.formatPageNumber(pageNumber);
IPagePreviewChanged listener;
synchronized (listeners) {
listener = listeners.get(page);
}
if (listener != null) {
showEmpty(listener);
queue(page);
}
}
public void reset() {
queue.shutdownNow();
synchronized (listeners) {
listeners.clear();
}
synchronized (cache) {
cache.clear();
}
queue = Executors.newFixedThreadPool(1);
}
public void setPreview(String pageNumber, IPagePreviewChanged listener) {
String page = Book2.formatPageNumber(pageNumber);
BufferedImage stored;
synchronized (listeners) {
listeners.put(page, listener);
}
synchronized (cache) {
stored = cache.get(page);
}
if (stored != null) {
listener.show(stored);
} else {
showEmpty(listener);
queue(page);
}
}
private void showEmpty(IPagePreviewChanged listener) {
listener.show(new BufferedImage(DataStorage.previewMaxWidth, DataStorage.previewMaxHeight,
BufferedImage.TYPE_INT_ARGB));
}
private void queue(String page) {
queue.submit(new Runnable() {
@Override
public void run() {
PageFileInfo pfi = new PageFileInfo(book, page);
BufferedImage result = pfi.constructPagePreview(DataStorage.previewMaxWidth,
DataStorage.previewMaxHeight);
synchronized (cache) {
cache.put(page, result);
}
IPagePreviewChanged listener;
synchronized (listeners) {
listener = listeners.get(page);
}
if (listener != null) {
listener.show(result);
}
}
});
}
}
| 3,700 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
IBookIterator.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/IBookIterator.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan;
/**
* Books iterator.
*
* @author Aleś Bułojčyk <alex73mail@gmail.com>
*/
public interface IBookIterator {
void onBook(Book2 book) throws Exception;
}
| 1,107 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
Context.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/Context.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan;
import java.io.File;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import javax.xml.bind.JAXBContext;
import org.alex73.skarynka.scan.xsd.Allow;
import org.alex73.skarynka.scan.xsd.Command;
import org.alex73.skarynka.scan.xsd.Config;
import org.alex73.skarynka.scan.xsd.OS;
import org.alex73.skarynka.scan.xsd.Param;
import org.alex73.skarynka.scan.xsd.Permissions;
import org.alex73.skarynka.scan.xsd.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Storage for common parameters and info.
*
* @author Aleś Bułojčyk <alex73mail@gmail.com>
*/
public class Context {
private static Logger LOG = LoggerFactory.getLogger(Context.class);
private static final JAXBContext CONTEXT;
public static final OS thisOS;
public static final String thisHost;
private static Map<String, String> settings;
private static Perm permissions;
private static Map<String, String> pageTags;
private static Map<String, String> processCommands;
static {
try {
CONTEXT = JAXBContext.newInstance(Config.class);
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
String osName = System.getProperty("os.name");
if (osName.startsWith("Windows")) {
thisOS = OS.WINDOWS;
} else if (osName.startsWith("Linux")) {
thisOS = OS.LINUX;
} else {
throw new ExceptionInInitializerError("Unknown OS");
}
thisHost = System.getProperty("HOST");
if (thisHost == null) {
throw new ExceptionInInitializerError("'HOST' was not defined");
}
}
public static void load() throws Exception {
Config config = (Config) CONTEXT.createUnmarshaller().unmarshal(new File("config.xml"));
Map<String, String> newSettings = new HashMap<>();
for (Param p : config.getSettings().getParam()) {
if (check(p.getOs(), p.getHost())) {
if (newSettings.put(p.getId(), p.getValue()) != null) {
throw new RuntimeException("Param '" + p.getId() + "' was already defined");
}
}
}
Perm newPermissions = null;
for (Permissions p : config.getPermissions()) {
if (check(p.getOs(), p.getHost())) {
if (newPermissions != null) {
throw new RuntimeException("Permissions was already defined");
}
newPermissions = new Perm();
for (Allow a : p.getAllow()) {
Field f = newPermissions.getClass().getField(a.getId());
f.setBoolean(newPermissions, a.isValue());
}
}
}
Map<String, String> newPageTags = new TreeMap<>();
for (Tag t : config.getPageTags().getTag()) {
if (newPageTags.put(t.getName(), t.getTitle()) != null) {
throw new RuntimeException("Page tag '" + t.getName() + "' defined twice");
}
}
Map<String, String> newProcessCommands = new TreeMap<>();
for (Command t : config.getProcessCommands().getCommand()) {
if (newProcessCommands.put(t.getName(), t.getTitle()) != null) {
throw new RuntimeException("Process command '" + t.getName() + "' defined twice");
}
}
settings = Collections.unmodifiableMap(newSettings);
permissions = newPermissions;
pageTags = Collections.unmodifiableMap(newPageTags);
processCommands = Collections.unmodifiableMap(newProcessCommands);
}
static boolean check(OS os, String host) {
if (os != null && !thisOS.equals(os)) {
return false;
}
if (host != null && !thisHost.equals(host)) {
return false;
}
return true;
}
public static String getBookDir() {
return settings.get("book-dir");
}
public static String getControlDir() {
return settings.get("control-dir");
}
public static Map<String, String> getSettings() {
return settings;
}
public static Perm getPermissions() {
return permissions;
}
public static Map<String, String> getPageTags() {
return pageTags;
}
public static Map<String, String> getProcessCommands() {
return processCommands;
}
public static class Perm {
public boolean CameraBadPixels, ProcessingBooks, ProcessingControls, ShowNonLocalBooks, BookControl, ShowDevices, ShowManualAdd;
}
public static class ScriptStorage {
public String name;
public String language;
public String script;
}
}
| 5,744 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
Config.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/xsd/Config.java |
package org.alex73.skarynka.scan.xsd;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{}settings"/>
* <element ref="{}permissions" maxOccurs="unbounded" minOccurs="0"/>
* <element ref="{}page-tags"/>
* <element ref="{}process-commands"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"settings",
"permissions",
"pageTags",
"processCommands"
})
@XmlRootElement(name = "config")
public class Config {
@XmlElement(required = true)
protected Settings settings;
protected List<Permissions> permissions;
@XmlElement(name = "page-tags", required = true)
protected PageTags pageTags;
@XmlElement(name = "process-commands", required = true)
protected ProcessCommands processCommands;
/**
* Gets the value of the settings property.
*
* @return
* possible object is
* {@link Settings }
*
*/
public Settings getSettings() {
return settings;
}
/**
* Sets the value of the settings property.
*
* @param value
* allowed object is
* {@link Settings }
*
*/
public void setSettings(Settings value) {
this.settings = value;
}
/**
* Gets the value of the permissions property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the permissions property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPermissions().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Permissions }
*
*
*/
public List<Permissions> getPermissions() {
if (permissions == null) {
permissions = new ArrayList<Permissions>();
}
return this.permissions;
}
/**
* Gets the value of the pageTags property.
*
* @return
* possible object is
* {@link PageTags }
*
*/
public PageTags getPageTags() {
return pageTags;
}
/**
* Sets the value of the pageTags property.
*
* @param value
* allowed object is
* {@link PageTags }
*
*/
public void setPageTags(PageTags value) {
this.pageTags = value;
}
/**
* Gets the value of the processCommands property.
*
* @return
* possible object is
* {@link ProcessCommands }
*
*/
public ProcessCommands getProcessCommands() {
return processCommands;
}
/**
* Sets the value of the processCommands property.
*
* @param value
* allowed object is
* {@link ProcessCommands }
*
*/
public void setProcessCommands(ProcessCommands value) {
this.processCommands = value;
}
}
| 3,793 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
ProcessScripts.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/xsd/ProcessScripts.java |
package org.alex73.skarynka.scan.xsd;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{}script" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"script"
})
@XmlRootElement(name = "process-scripts")
public class ProcessScripts {
protected List<Script> script;
/**
* Gets the value of the script property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the script property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getScript().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Script }
*
*
*/
public List<Script> getScript() {
if (script == null) {
script = new ArrayList<Script>();
}
return this.script;
}
}
| 1,760 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
Command.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/xsd/Command.java |
package org.alex73.skarynka.scan.xsd;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attribute name="name" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="title" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "command")
public class Command {
@XmlAttribute(name = "name", required = true)
protected String name;
@XmlAttribute(name = "title", required = true)
protected String title;
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the title property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTitle() {
return title;
}
/**
* Sets the value of the title property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTitle(String value) {
this.title = value;
}
}
| 2,016 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
Set.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/xsd/Set.java |
package org.alex73.skarynka.scan.xsd;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <simpleContent>
* <extension base="<http://www.w3.org/2001/XMLSchema>string">
* <attribute name="host" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="os" type="{}OS" />
* <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* </extension>
* </simpleContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"value"
})
@XmlRootElement(name = "set")
public class Set {
@XmlValue
protected String value;
@XmlAttribute(name = "host")
protected String host;
@XmlAttribute(name = "os")
protected OS os;
@XmlAttribute(name = "id", required = true)
protected String id;
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValue(String value) {
this.value = value;
}
/**
* Gets the value of the host property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getHost() {
return host;
}
/**
* Sets the value of the host property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHost(String value) {
this.host = value;
}
/**
* Gets the value of the os property.
*
* @return
* possible object is
* {@link OS }
*
*/
public OS getOs() {
return os;
}
/**
* Sets the value of the os property.
*
* @param value
* allowed object is
* {@link OS }
*
*/
public void setOs(OS value) {
this.os = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
}
| 3,017 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
ProcessCommands.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/xsd/ProcessCommands.java |
package org.alex73.skarynka.scan.xsd;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{}command" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"command"
})
@XmlRootElement(name = "process-commands")
public class ProcessCommands {
protected List<Command> command;
/**
* Gets the value of the command property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the command property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCommand().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Command }
*
*
*/
public List<Command> getCommand() {
if (command == null) {
command = new ArrayList<Command>();
}
return this.command;
}
}
| 1,776 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
Allow.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/xsd/Allow.java |
package org.alex73.skarynka.scan.xsd;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="value" use="required" type="{http://www.w3.org/2001/XMLSchema}boolean" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "allow")
public class Allow {
@XmlAttribute(name = "id", required = true)
protected String id;
@XmlAttribute(name = "value", required = true)
protected boolean value;
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the value property.
*
*/
public boolean isValue() {
return value;
}
/**
* Sets the value of the value property.
*
*/
public void setValue(boolean value) {
this.value = value;
}
}
| 1,825 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
Tag.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/xsd/Tag.java |
package org.alex73.skarynka.scan.xsd;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attribute name="name" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="title" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "tag")
public class Tag {
@XmlAttribute(name = "name", required = true)
protected String name;
@XmlAttribute(name = "title", required = true)
protected String title;
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the title property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTitle() {
return title;
}
/**
* Sets the value of the title property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTitle(String value) {
this.title = value;
}
}
| 2,008 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
Param.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/xsd/Param.java |
package org.alex73.skarynka.scan.xsd;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <simpleContent>
* <extension base="<http://www.w3.org/2001/XMLSchema>string">
* <attribute name="host" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="os" type="{}OS" />
* <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* </extension>
* </simpleContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"value"
})
@XmlRootElement(name = "param")
public class Param {
@XmlValue
protected String value;
@XmlAttribute(name = "host")
protected String host;
@XmlAttribute(name = "os")
protected OS os;
@XmlAttribute(name = "id", required = true)
protected String id;
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValue(String value) {
this.value = value;
}
/**
* Gets the value of the host property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getHost() {
return host;
}
/**
* Sets the value of the host property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHost(String value) {
this.host = value;
}
/**
* Gets the value of the os property.
*
* @return
* possible object is
* {@link OS }
*
*/
public OS getOs() {
return os;
}
/**
* Sets the value of the os property.
*
* @param value
* allowed object is
* {@link OS }
*
*/
public void setOs(OS value) {
this.os = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
}
| 3,021 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
PageTags.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/xsd/PageTags.java |
package org.alex73.skarynka.scan.xsd;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{}tag" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"tag"
})
@XmlRootElement(name = "page-tags")
public class PageTags {
protected List<Tag> tag;
/**
* Gets the value of the tag property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the tag property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getTag().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Tag }
*
*
*/
public List<Tag> getTag() {
if (tag == null) {
tag = new ArrayList<Tag>();
}
return this.tag;
}
}
| 1,706 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
Script.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/xsd/Script.java |
package org.alex73.skarynka.scan.xsd;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <simpleContent>
* <extension base="<http://www.w3.org/2001/XMLSchema>string">
* <attribute name="language" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="name" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="host" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="os" type="{}OS" />
* </extension>
* </simpleContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"value"
})
@XmlRootElement(name = "script")
public class Script {
@XmlValue
protected String value;
@XmlAttribute(name = "language", required = true)
protected String language;
@XmlAttribute(name = "name", required = true)
protected String name;
@XmlAttribute(name = "host")
protected String host;
@XmlAttribute(name = "os")
protected OS os;
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValue(String value) {
this.value = value;
}
/**
* Gets the value of the language property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLanguage() {
return language;
}
/**
* Sets the value of the language property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLanguage(String value) {
this.language = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the host property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getHost() {
return host;
}
/**
* Sets the value of the host property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHost(String value) {
this.host = value;
}
/**
* Gets the value of the os property.
*
* @return
* possible object is
* {@link OS }
*
*/
public OS getOs() {
return os;
}
/**
* Sets the value of the os property.
*
* @param value
* allowed object is
* {@link OS }
*
*/
public void setOs(OS value) {
this.os = value;
}
}
| 3,695 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
ObjectFactory.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/xsd/ObjectFactory.java |
package org.alex73.skarynka.scan.xsd;
import javax.xml.bind.annotation.XmlRegistry;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the org.alex73.skarynka.scan.xsd package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.alex73.skarynka.scan.xsd
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link Allow }
*
*/
public Allow createAllow() {
return new Allow();
}
/**
* Create an instance of {@link Settings }
*
*/
public Settings createSettings() {
return new Settings();
}
/**
* Create an instance of {@link Param }
*
*/
public Param createParam() {
return new Param();
}
/**
* Create an instance of {@link Permissions }
*
*/
public Permissions createPermissions() {
return new Permissions();
}
/**
* Create an instance of {@link PageTags }
*
*/
public PageTags createPageTags() {
return new PageTags();
}
/**
* Create an instance of {@link Tag }
*
*/
public Tag createTag() {
return new Tag();
}
/**
* Create an instance of {@link ProcessCommands }
*
*/
public ProcessCommands createProcessCommands() {
return new ProcessCommands();
}
/**
* Create an instance of {@link Command }
*
*/
public Command createCommand() {
return new Command();
}
/**
* Create an instance of {@link Config }
*
*/
public Config createConfig() {
return new Config();
}
}
| 2,224 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
Settings.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/xsd/Settings.java |
package org.alex73.skarynka.scan.xsd;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{}param" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"param"
})
@XmlRootElement(name = "settings")
public class Settings {
protected List<Param> param;
/**
* Gets the value of the param property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the param property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getParam().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Param }
*
*
*/
public List<Param> getParam() {
if (param == null) {
param = new ArrayList<Param>();
}
return this.param;
}
}
| 1,733 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
OS.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/xsd/OS.java |
package org.alex73.skarynka.scan.xsd;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for OS.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="OS">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="Linux"/>
* <enumeration value="Windows"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "OS")
@XmlEnum
public enum OS {
@XmlEnumValue("Linux")
LINUX("Linux"),
@XmlEnumValue("Windows")
WINDOWS("Windows");
private final String value;
OS(String v) {
value = v;
}
public String value() {
return value;
}
public static OS fromValue(String v) {
for (OS c: OS.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
| 1,062 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
Permissions.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/xsd/Permissions.java |
package org.alex73.skarynka.scan.xsd;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{}allow" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* <attribute name="host" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="os" type="{}OS" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"allow"
})
@XmlRootElement(name = "permissions")
public class Permissions {
protected List<Allow> allow;
@XmlAttribute(name = "host")
protected String host;
@XmlAttribute(name = "os")
protected OS os;
/**
* Gets the value of the allow property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the allow property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAllow().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Allow }
*
*
*/
public List<Allow> getAllow() {
if (allow == null) {
allow = new ArrayList<Allow>();
}
return this.allow;
}
/**
* Gets the value of the host property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getHost() {
return host;
}
/**
* Sets the value of the host property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHost(String value) {
this.host = value;
}
/**
* Gets the value of the os property.
*
* @return
* possible object is
* {@link OS }
*
*/
public OS getOs() {
return os;
}
/**
* Sets the value of the os property.
*
* @param value
* allowed object is
* {@link OS }
*
*/
public void setOs(OS value) {
this.os = value;
}
}
| 2,884 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
ImageViewPane.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/common/ImageViewPane.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan.common;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.ByteLookupTable;
import java.awt.image.LookupOp;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Widget for display page with ability to proportional scale, crop, rotate,
* etc.
*
* @author Aleś Bułojčyk <alex73mail@gmail.com>
*/
@SuppressWarnings("serial")
public class ImageViewPane extends JComponent {
private static Logger LOG = LoggerFactory.getLogger(ImageViewPane.class);
private volatile BufferedImage img;
private volatile String pageNumber;
private int rotation;
private boolean mirrorHorizontal, mirrorVertical, inverted;
private boolean strikeout;
double sourceAspectWidth = 1;
double sourceAspectHeight = 1;
private AffineTransform transform;
private Dimension imageSize;
private List<Rectangle2D.Double> crops = new ArrayList<>();
public int getRotation() {
return rotation;
}
public void setRotation(int r) {
this.rotation = r;
repaint();
}
public void setMirrorHorizontal(boolean mirrorHorizontal) {
this.mirrorHorizontal = mirrorHorizontal;
repaint();
}
public void setMirrorVertical(boolean mirrorVertical) {
this.mirrorVertical = mirrorVertical;
repaint();
}
public void setInverted(boolean inverted) {
this.inverted = inverted;
repaint();
}
public boolean getStrikeOut() {
return strikeout;
}
public void setStrikeout(boolean strikeout) {
this.strikeout = strikeout;
repaint();
}
public void displayImage(BufferedImage image, double aspectWidth, double aspectHeight) {
this.img = image;
sourceAspectWidth = aspectWidth;
sourceAspectHeight = aspectHeight;
repaint();
}
public BufferedImage getImage() {
return img;
}
public String getPageNumber() {
return pageNumber;
}
public void setPageNumber(String pageNumber) {
this.pageNumber = pageNumber;
repaint();
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
// need to remember image locally because other thread can replace it
BufferedImage image = inverted ? invert(img) : img;
if (image != null) {
paintImage(g2, image, sourceAspectWidth, sourceAspectHeight, rotation);
}
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f));
String p = pageNumber;
if (p != null && p.length() > 0) {
g2.setColor(Color.RED);
paintPageNumber(g2, p);
}
for(Rectangle2D.Double crop:crops) {
drawCropRectangle(g2, img, crop, transform);
}
if (strikeout) {
g2.setColor(Color.RED);
g2.setStroke(new BasicStroke(10));
g2.drawLine(0, 0, getWidth(), getHeight());
g2.drawLine(getWidth(), 0, 0, getHeight());
}
}
/**
* Draw image to center of panel with scale for maximaze with aspect ratio
* preserve.
*
* @param g2
* output graphics
* @param img
* source image
* @param sourceScaleWidth
* source image width scale factor
* @param sourceScaleHeight
* source image height scale factor
* @param rotation
* number of 90 gradus rotation clockwise, as for {see
* java.awt.geom.AffineTransform#quadrantRotate(int
* numquadrants)}
*/
private void paintImage(Graphics2D g2, BufferedImage img, double sourceScaleWidth, double sourceScaleHeight,
int rotation) {
transform = getAffineTransform(sourceScaleWidth, sourceScaleHeight, rotation, mirrorHorizontal, mirrorVertical, img, getWidth(), getHeight());
imageSize = new Dimension(img.getWidth(), img.getHeight());
// draw
AffineTransform prev = g2.getTransform();
try {
AffineTransform c = new AffineTransform(prev);
c.concatenate(transform);
g2.setTransform(c);
g2.drawImage(img, 0, 0, null);
} finally {
g2.setTransform(prev);
}
}
public static void drawCropRectangle(Graphics2D g2, BufferedImage image, Rectangle2D.Double crop,
AffineTransform transform) {
try {
double x1, y1, x2, y2;
x1 = crop.getMinX() * image.getWidth();
y1 = crop.getMinY() * image.getHeight();
x2 = crop.getMaxX() * image.getWidth();
y2 = crop.getMaxY() * image.getHeight();
if (LOG.isTraceEnabled()) {
LOG.trace("Crop rectangle in image pixels: " + x1 + "," + y1 + " - " + x2 + "," + y2);
}
Point2D.Double p1 = new Point2D.Double();
Point2D.Double p2 = new Point2D.Double();
transform.transform(new Point2D.Double(x1, y1), p1);
transform.transform(new Point2D.Double(x2, y2), p2);
Rectangle2D.Double drawRect = new Rectangle2D.Double(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y);
if (drawRect.width < 0) {
drawRect.width = -drawRect.width;
drawRect.x -= drawRect.width;
}
if (drawRect.height < 0) {
drawRect.height = -drawRect.height;
drawRect.y -= drawRect.height;
}
if (crop.getMinX() < 0 || crop.getMinY() < 0 || crop.getMaxX() > 1 || crop.getMaxY() > 1) {
// out of real image
g2.setColor(Color.YELLOW);
} else {
g2.setColor(Color.RED);
}
int x = (int) Math.round(drawRect.x);
int y = (int) Math.round(drawRect.y);
int w = (int) Math.round(drawRect.width);
int h = (int) Math.round(drawRect.height);
g2.drawRect(x, y, w, h);
} catch (Exception ex) {
LOG.error("Error convert image to mouse coordinates", ex);
}
}
public static BufferedImage invert(BufferedImage img) {
byte reverse[] = new byte[256];
for (int i = 0; i < 256; i++) {
reverse[i] = (byte) (255 - i);
}
ByteLookupTable lookupTable = new ByteLookupTable(0, reverse);
LookupOp lop = new LookupOp(lookupTable, null);
return lop.filter(img, null);
}
private void paintPageNumber(Graphics2D g2, String page) {
Font font = new Font(Font.SERIF, Font.PLAIN, 120);
int baseLine = font.getBaselineFor(page.charAt(0));
g2.setFont(font);
Rectangle2D bounds = g2.getFontMetrics().getStringBounds(page, g2);
g2.drawString(page, Math.round((getWidth() - bounds.getWidth()) / 2), getHeight() - baseLine - 20);
}
public static AffineTransform getAffineTransform(double sourceScaleWidth, double sourceScaleHeight, int rotation, boolean mirrorHorizontal, boolean mirrorVertical,
BufferedImage img, int outputWidth, int outputHeight) {
if (sourceScaleWidth < 0.01 || sourceScaleWidth > 100) {
throw new IllegalArgumentException("Wrong source scale width");
}
if (sourceScaleHeight < 0.01 || sourceScaleHeight > 100) {
throw new IllegalArgumentException("Wrong source scale height");
}
if (rotation < 0 || rotation > 3) {
throw new IllegalArgumentException("Wrong rotation");
}
// define width and height for image with source scale factor and
// rotation
double willWidth = 0, willHeight = 0;
switch (rotation) {
case 0:
case 2:
willWidth = img.getWidth() * sourceScaleWidth;
willHeight = img.getHeight() * sourceScaleHeight;
break;
case 1:
case 3:
willWidth = img.getHeight() * sourceScaleHeight;
willHeight = img.getWidth() * sourceScaleWidth;
break;
}
// define scale factor for maximize image in panel
double scaleForMaximizeInside = Math.min(outputWidth / willWidth, outputHeight / willHeight);
willWidth *= scaleForMaximizeInside;
willHeight *= scaleForMaximizeInside;
// define offset for place image to center of panel
double offX = (outputWidth - willWidth) / 2;
double offY = (outputHeight - willHeight) / 2;
// create transformation
AffineTransform at = new AffineTransform();
at.translate(willWidth / 2 + offX, willHeight / 2 + offY);
at.quadrantRotate(rotation);
at.scale(sourceScaleWidth * scaleForMaximizeInside, sourceScaleHeight * scaleForMaximizeInside);
at.translate(-img.getWidth() / 2, -img.getHeight() / 2);
if (mirrorHorizontal) {
at.scale(-1, 1);
at.translate(-img.getWidth(), 0);
}
if (mirrorVertical) {
at.scale(1, -1);
at.translate(0, -img.getHeight());
}
return at;
}
public Point mouseToImage(Point mouse, int offX, int offY, Dimension fullImageSize) {
try {
Point2D p = new Point2D.Double();
Point m = new Point(mouse.x - offX, mouse.y - offY);
transform.inverseTransform(m, p);
int x = (int) Math.round(p.getX() / imageSize.width * fullImageSize.width);
int y = (int) Math.round(p.getY() / imageSize.height * fullImageSize.height);
if (x < 0) {
x = 0;
}
if (y < 0) {
y = 0;
}
if (x > fullImageSize.width) {
x = fullImageSize.width;
}
if (y > fullImageSize.height) {
y = fullImageSize.height;
}
return new Point(x, y);
} catch (Exception ex) {
LOG.error("Error convert mouse to image coordinates", ex);
return null;
}
}
public List<Rectangle2D.Double> getCrops() {
return crops;
}
public Rectangle getImageRect(Rectangle2D.Double crop) {
double x1, y1, x2, y2;
x1 = crop.getMinX() * img.getWidth();
y1 = crop.getMinY() * img.getHeight();
x2 = crop.getMaxX() * img.getWidth();
y2 = crop.getMaxY() * img.getHeight();
Rectangle2D.Double drawRect = new Rectangle2D.Double(x1, y1, x2 - x1, y2 - y1);
if (drawRect.width < 0) {
drawRect.width = -drawRect.width;
drawRect.x -= drawRect.width;
}
if (drawRect.height < 0) {
drawRect.height = -drawRect.height;
drawRect.y -= drawRect.height;
}
return drawRect.getBounds();
}
public Rectangle2D.Double screen2image(Rectangle cropRectangle, Dimension fullImageSize) {
Rectangle2D.Double crop = new Rectangle2D.Double();
crop.x = cropRectangle.getX() / fullImageSize.width;
crop.y = cropRectangle.getY() / fullImageSize.height;
crop.width = (cropRectangle.getX() + cropRectangle.getWidth()) / fullImageSize.width - crop.x;
crop.height = (cropRectangle.getY() + cropRectangle.getHeight()) / fullImageSize.height - crop.y;
if (LOG.isTraceEnabled()) {
LOG.info("Crop rectangle in 0..1: " + crop);
}
return crop;
}
}
| 12,769 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
PropsetUtils.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/propsets/PropsetUtils.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan.propsets;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.IOUtils;
/**
* Util for load propset values from propsetN.lua file.
*
* @author Aleś Bułojčyk <alex73mail@gmail.com>
*/
public class PropsetUtils {
static final Pattern RE_PROP = Pattern.compile("\\s*([A-Z][A-Z_0-9]*)\\s*=\\s*([0-9]+)\\s*,.*");
public static Map<String, Integer> getPropset(int propsetNumber) throws IOException {
Map<String, Integer> result = new TreeMap<>();
try (InputStream in = PropsetUtils.class.getResourceAsStream("propset" + propsetNumber + ".lua")) {
for (String line : IOUtils.readLines(in, "UTF-8")) {
Matcher m = RE_PROP.matcher(line);
if (m.matches()) {
result.put(m.group(1), Integer.parseInt(m.group(2)));
}
}
}
return result;
}
}
| 1,961 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
ProcessCommands.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/process/ProcessCommands.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan.process;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ProcessCommands {
private static Logger LOG = LoggerFactory.getLogger(ProcessCommands.class);
static final Pattern DO_LS = Pattern.compile("ls\\s+(.+)");
static final Pattern DO_DF = Pattern.compile("df\\s+(.+)");
static final Pattern DO_RM = Pattern.compile("rm\\s+(.+)");
static final Pattern DO_CP = Pattern.compile("cp\\s+(.+)\\s+(.+)");
static final Pattern DO_MVDIR = Pattern.compile("mvdir\\s+(.+)\\s+(.+)");
static final Pattern DO_SCANS = Pattern.compile("scans");
static final Pattern DO_EXEC = Pattern.compile("exec\\s+(.+)");
public static String call(String s) throws Exception {
LOG.info("Parse command: " + s);
StringBuilder out = new StringBuilder();
Matcher m;
if ((m = DO_LS.matcher(s)).matches()) {
LOG.info("Command ls " + m.group(1));
List<File> files = new ArrayList<>(FileUtils.listFiles(new File(m.group(1)), null, true));
Collections.sort(files);
out.append(s + ":\n");
for (File f : files) {
out.append(" " + f.getPath() + " " + f.length() + "\n");
}
} else if ((m = DO_DF.matcher(s)).matches()) {
LOG.info("Command df " + m.group(1));
File f = new File(m.group(1));
long gb = f.getFreeSpace() / 1024 / 1024 / 1024;
out.append(s + ": " + gb + " gb\n");
} else if ((m = DO_RM.matcher(s)).matches()) {
LOG.info("Command rm " + m.group(1));
File f = new File(m.group(1));
if (f.isDirectory()) {
FileUtils.deleteDirectory(f);
} else {
f.delete();
}
} else if ((m = DO_CP.matcher(s)).matches()) {
LOG.info("Command cp " + m.group(1) + " " + m.group(2));
FileUtils.copyFile(new File(m.group(1)), new File(m.group(2)));
} else if ((m = DO_MVDIR.matcher(s)).matches()) {
LOG.info("Command mvdir " + m.group(1) + " " + m.group(2));
FileUtils.moveDirectoryToDirectory(new File(m.group(1)), new File(m.group(2)), true);
} else {
throw new Exception("Unknown command: " + s);
}
return out.toString();
}
}
| 3,163 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
ProcessDaemon.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/process/ProcessDaemon.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan.process;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import org.alex73.skarynka.scan.Book2;
import org.alex73.skarynka.scan.Context;
import org.alex73.skarynka.scan.process.pdf.PdfCreator;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ProcessDaemon extends Thread {
private static Logger LOG = LoggerFactory.getLogger(ProcessDaemon.class);
private static Charset UTF8 = Charset.forName("UTF-8");
private boolean finish;
private boolean paused;
private Script currentScript;
public void finish() {
synchronized (this) {
finish = true;
notifyAll();
}
}
public void setPaused(boolean p) {
paused = p;
}
@Override
public void run() {
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
LOG.info("ProcessDaemon started");
while (!finish) {
try {
boolean processed = process();
if (!finish) {
synchronized (this) {
wait(processed ? 50 : 10000);
}
}
} catch (Throwable ex) {
LOG.error("Error process", ex);
}
}
}
boolean process() throws Exception {
LOG.debug("check for processing...");
if (Context.getPermissions().ProcessingControls && Context.getControlDir() != null) {
// process control files
LOG.trace("check for control dir " + Context.getControlDir());
File[] controls = new File(Context.getControlDir()).listFiles(new FileFilter() {
public boolean accept(File file) {
return file.isFile() && file.getName().endsWith(".do");
}
});
if (controls != null) {
LOG.trace("control files found: " + controls.length);
for (File c : controls) {
LOG.trace("check for control file " + c);
File errorFile = new File(c.getPath() + ".err");
File outFile = new File(c.getPath() + ".out");
if (errorFile.exists() || outFile.exists()) {
continue;
}
try {
String cmd = FileUtils.readFileToString(c, "UTF-8");
String result = ProcessCommands.call(cmd);
FileUtils.writeStringToFile(outFile, result, "UTF-8");
} catch (Throwable ex) {
FileUtils.writeStringToFile(errorFile, ex.getMessage(), "UTF-8");
}
}
}
}
if (paused) {
return false;
}
if (Context.getPermissions().ProcessingBooks) {
// process books
LOG.trace("check for book dir " + Context.getBookDir());
File[] ls = new File(Context.getBookDir()).listFiles(new FileFilter() {
public boolean accept(File pathname) {
return pathname.isDirectory() && new File(pathname, "book.properties").isFile();
}
});
if (ls == null) {
LOG.trace("books not found");
return false;
}
int count = 0;
for (File d : ls) {
LOG.trace("check for book dir " + d);
File processFile = new File(d, ".process");
if (!processFile.exists()) {
// processing wasn't started yet
continue;
}
File processDoneFile = new File(d, ".process.done");
if (processDoneFile.exists()) {
// processing finished
continue;
}
File errorFile = new File(d, ".errors");
if (errorFile.exists()) {
// if book contains error files - skip this book
continue;
}
LOG.debug("Process book " + d);
Book2 book = new Book2(d);
if (!book.getErrors().isEmpty()) {
FileUtils.writeStringToFile(errorFile, "Error read book: " + book.getErrors(), UTF8);
continue;
}
String command = FileUtils.readFileToString(processFile, UTF8);
Script newScript;
try {
// update compiled script if script file was updated
newScript = new Script(command);
if (currentScript == null || !currentScript.theSame(newScript)) {
currentScript = newScript;
currentScript.compile();
}
} catch (Throwable ex) {
FileUtils.writeStringToFile(errorFile, "Error get script: " + ex.getMessage(), UTF8);
continue;
}
currentScript.makeTemp(book);
boolean wasError = false;
for (String p : book.listPages()) {
if (finish) {
return false;
}
// PageFileInfo pfi = new PageFileInfo(book, p);
try {
if (currentScript.pageResultExist(book, p)) {
continue;
}
currentScript.pageExecute(book, p);
count++;
} catch (Throwable ex) {
LOG.info("Error process page " + p, ex);
FileUtils.writeStringToFile(errorFile,
"Error process page #" + p + ": " + ex.getMessage(), UTF8);
wasError = true;
break;
}
if (count >= 5) {
return true;
}
}
// pages process was finished - need to finish book
try {
if (!wasError) {
if (!currentScript.bookResultExist(book)) {
currentScript.bookExecute(book);
}
currentScript.removeTemp(book);
}
} catch (Throwable ex) {
LOG.info("Error process book", ex);
FileUtils.writeStringToFile(errorFile, "Error process book: " + ex.getMessage(), UTF8);
wasError = true;
break;
}
if (!wasError) {
// book finished without errors
processFile.renameTo(processDoneFile);
}
}
}
return false;
}
public static class PageContext {
private final Book2 book;
private final String page;
private final Book2.PageInfo pi;
private final Map<String, Boolean> tags;
public PageContext(Book2 book, String page) {
this.book = book;
this.page = Book2.formatPageNumber(page);
this.pi = book.getPageInfo(this.page);
Map<String, Boolean> tags = new TreeMap<>();
for (String t : pi.tags) {
tags.put(t, true);
}
this.tags = Collections.unmodifiableMap(tags);
}
public String getNumber() {
return page;
}
public Map<String, Boolean> getTags() {
return tags;
}
public int getCropPosX() {
return pi.cropPosX;
}
public int getCropPosY() {
return pi.cropPosY;
}
public int getRotate() {
return pi.rotate;
}
public String getCamera() {
return pi.camera;
}
public int getImageSizeX() {
return pi.imageSizeX;
}
public int getImageSizeY() {
return pi.imageSizeY;
}
public String getOriginalPageFile() {
return page + '.' + pi.pageOriginalFileExt;
}
public String getPreviewPageFile() {
return getOriginalPageFile() + ".preview.jpg";
}
}
public static class BookContext {
private final Book2 book;
public BookContext(Book2 book) {
this.book = book;
}
public Book2 getBook() {
return book;
}
public String getName() {
return book.getName();
}
public int getScale() {
return book.scale;
}
public int getDpi() {
return book.dpi;
}
public int getCropSizeX() {
return book.cropSizeX;
}
public int getCropSizeY() {
return book.cropSizeY;
}
public List<String> getPages() {
return book.listPages();
}
}
public static class CommandContext {
private final Book2 book;
private final Bindings bindings;
public CommandContext(Book2 book, Bindings bindings) {
this.book = book;
this.bindings = bindings;
}
public boolean fileExist(String name) {
return new File(book.getBookDir(), name).exists();
}
public boolean fileRemove(String name) {
return new File(book.getBookDir(), name).delete();
}
static final Pattern RE_VAR = Pattern.compile("\\$\\{.+?\\}");
public void exec(String cmd) throws Exception {
StringBuilder cmdo = new StringBuilder();
Matcher m = RE_VAR.matcher(cmd);
int prev = 0;
while (m.find(prev)) {
cmdo.append(cmd.substring(prev, m.start()));
String var = cmd.substring(m.start() + 2, m.end() - 1);
cmdo.append(BeanUtils.getProperty(bindings, var));
prev = m.end();
}
cmdo.append(cmd.substring(prev));
String[] cmda;
switch (Context.thisOS) {
case LINUX:
cmda = new String[] { "nice", "ionice", "-c3", "sh", "-c", cmdo.toString() };
break;
case WINDOWS:
cmda = new String[] { "cmd.exe", "/c", cmdo.toString() };
break;
default:
throw new Exception("Unknown OS");
}
LOG.debug("Execute for book " + book.getName() + ": " + cmdo);
Process process = Runtime.getRuntime().exec(cmda, null, book.getBookDir());
int r = process.waitFor();
LOG.debug("Execution result: " + r);
if (r != 0) {
String err = IOUtils.toString(process.getErrorStream(),
Context.getSettings().get("command_charset"));
throw new Exception("Error execution " + Arrays.toString(cmda) + ": " + r + " / " + err);
}
}
public void pdf(String bookOutPath, String imagesDirPath, String imagesExt) throws Exception {
File outFile = new File(book.getBookDir(), bookOutPath);
File imagesDir = new File(book.getBookDir(), imagesDirPath);
File[] jpegs = imagesDir.listFiles(new FileFilter() {
@Override
public boolean accept(File f) {
return f.isFile() && f.getName().endsWith("." + imagesExt);
}
});
Arrays.sort(jpegs);
PdfCreator.create(outFile, jpegs);
}
public String getExecDir() {
return new File(".").getAbsolutePath();
}
public PdfCreator pdf2(String bookOutPath) throws Exception {
File outFile = new File(book.getBookDir(), bookOutPath);
return new PdfCreator(outFile);
}
}
public static class Script {
public final String script;
public final String command;
public ScriptEngine engine;
public CompiledScript csPreview;
public CompiledScript csPageResultExists;
public CompiledScript csPageExecute;
public CompiledScript csBookResultExists;
public CompiledScript csBookExecute;
public Script(String command) throws Exception {
this.script = FileUtils.readFileToString(new File("process.js"), "UTF-8");
this.command = command;
}
public boolean theSame(Script obj) {
return script.equals(obj.script) && command.equals(obj.command);
}
public void compilePreview() throws Exception {
engine = new ScriptEngineManager().getEngineByName("nashorn");
csPreview = ((Compilable) engine).compile(script + "\n command_preview();");
}
public void execPreview(Book2 book, String page) throws Exception {
Bindings bindings = engine.createBindings();
bindings.put("settings", Context.getSettings());
bindings.put("page", new PageContext(book, page));
bindings.put("book", new BookContext(book));
bindings.put("cmd", new CommandContext(book, bindings));
csPreview.eval(bindings);
}
public void compile() throws Exception {
engine = new ScriptEngineManager().getEngineByName("nashorn");
csPageResultExists = ((Compilable) engine).compile(script + "\n exist_" + command + "();");
csPageExecute = ((Compilable) engine).compile(script + "\n execute_" + command + "();");
csBookResultExists = ((Compilable) engine).compile(script + "\n bookexist_" + command + "();");
csBookExecute = ((Compilable) engine).compile(script + "\n bookexecute_" + command + "();");
}
public boolean pageResultExist(Book2 book, String page) throws Exception {
Bindings bindings = engine.createBindings();
bindings.put("settings", Context.getSettings());
bindings.put("page", new PageContext(book, page));
bindings.put("book", new BookContext(book));
bindings.put("cmd", new CommandContext(book, bindings));
return (boolean) csPageResultExists.eval(bindings);
}
public void pageExecute(Book2 book, String page) throws Exception {
Bindings bindings = engine.createBindings();
bindings.put("settings", Context.getSettings());
bindings.put("page", new PageContext(book, page));
bindings.put("book", new BookContext(book));
bindings.put("cmd", new CommandContext(book, bindings));
csPageExecute.eval(bindings);
}
public boolean bookResultExist(Book2 book) throws Exception {
Bindings bindings = engine.createBindings();
bindings.put("settings", Context.getSettings());
bindings.put("book", new BookContext(book));
bindings.put("cmd", new CommandContext(book, bindings));
return (boolean) csBookResultExists.eval(bindings);
}
public void bookExecute(Book2 book) throws Exception {
Bindings bindings = engine.createBindings();
bindings.put("settings", Context.getSettings());
bindings.put("book", new BookContext(book));
bindings.put("cmd", new CommandContext(book, bindings));
csBookExecute.eval(bindings);
}
public void makeTemp(Book2 book) {
new File(book.getBookDir(), "temp").mkdirs();
}
public void removeTemp(Book2 book) throws IOException {
FileUtils.deleteDirectory(new File(book.getBookDir(), "temp"));
}
}
private static Script previewScript;
public static synchronized void createPreviewIfNeed(Book2 book, String page) {
try {
if (previewScript == null) {
previewScript = new ProcessDaemon.Script("preview");
previewScript.compilePreview();
}
PageFileInfo pfi = new PageFileInfo(book, page);
if (!pfi.getPreviewFile().exists()) {
updatePageSize(book, page);
previewScript.execPreview(book, page);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static synchronized void updatePageSize(Book2 book, String page) throws Exception {
Book2.PageInfo pi = book.getPageInfo(page);
PageFileInfo pfi = new PageFileInfo(book, page);
try (ImageInputStream iis = ImageIO.createImageInputStream(pfi.getOriginalFile())) {
Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
if (!readers.hasNext()) {
throw new Exception("Error read image file meta: " + pfi.getOriginalFile().getAbsolutePath());
}
ImageReader rd = readers.next();
rd.setInput(iis, true);
pi.imageSizeX = rd.getWidth(0);
pi.imageSizeY = rd.getHeight(0);
}
}
}
| 18,821 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
PageFileInfo.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/process/PageFileInfo.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan.process;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.List;
import javax.imageio.ImageIO;
import org.alex73.skarynka.scan.Book2;
import org.alex73.skarynka.scan.common.ImageViewPane;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//cmd.add("-adaptive-resize");
// dcraw -W -b value - for custom brightness
public class PageFileInfo {
private static Logger LOG = LoggerFactory.getLogger(PageFileInfo.class);
private final Book2 book;
private final Book2.PageInfo pi;
private final String page;
public PageFileInfo(Book2 book, String page) {
this.book = book;
this.page = Book2.formatPageNumber(page);
pi = book.getPageInfo(this.page);
if (pi == null) {
throw new RuntimeException("Page not found");
}
}
public Book2.PageInfo getPageInfo() {
return pi;
}
public File getPreviewFile() {
return new File(book.getBookDir(), "preview/" + page + ".jpg");
}
public File getOriginalFile() {
return new File(book.getBookDir(), page + '.' + pi.pageOriginalFileExt);
}
public File getRawFile() {
return new File(book.getBookDir(), page + ".raw");
}
public File getEditFile() {
return new File(book.getBookDir(), page + "-edit.png");
}
public File getDjvuFile() {
return new File(book.getBookDir(), page + ".djvu");
}
public File getJp2File() {
return new File(book.getBookDir(), page + ".jp2");
}
void addRotate(List<String> cmdConvert, int rotate) {
switch (rotate) {
case 0:
break;
case 1:
cmdConvert.add("-rotate");
cmdConvert.add("90");
break;
case 2:
cmdConvert.add("-rotate");
cmdConvert.add("180");
break;
case 3:
cmdConvert.add("-rotate");
cmdConvert.add("270");
break;
default:
throw new RuntimeException("Unknown rotate: " + rotate);
}
}
void addResize(List<String> cmdConvert, int scale) {
if (scale != 0) {
cmdConvert.add("-adaptive-resize");
cmdConvert.add(scale + "%");
}
}
public BufferedImage constructPagePreview(int maxWidth, int maxHeight) {
BufferedImage img;
File jpeg = getPreviewFile();
if (!jpeg.exists()) {
return createErrorImage(maxWidth, maxHeight);
}
try {
img = ImageIO.read(jpeg);
} catch (Exception ex) {
LOG.info("Error read page for preview: " + page, ex);
return createErrorImage(maxWidth, maxHeight);
}
BufferedImage result = new BufferedImage(maxWidth, maxHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = result.createGraphics();
AffineTransform transform = ImageViewPane.getAffineTransform(1, 1, pi.rotate, pi.mirrorHorizontal, pi.mirrorVertical, img, maxWidth, maxHeight);
AffineTransform prev = g.getTransform();
try {
g.setTransform(transform);
g.drawImage(img, 0, 0, null);
} finally {
g.setTransform(prev);
}
Rectangle2D.Double crop = new Rectangle2D.Double();
crop.x = 1.0 * pi.cropPosX / pi.imageSizeX;
crop.y = 1.0 * pi.cropPosY / pi.imageSizeY;
crop.width = 1.0 * (pi.cropPosX + book.cropSizeX) / pi.imageSizeX - crop.x;
crop.height = 1.0 * (pi.cropPosY + book.cropSizeY) / pi.imageSizeY - crop.y;
ImageViewPane.drawCropRectangle(g, img, crop, transform);
g.dispose();
// if (pi.inverted) {
// for (int x = 0; x < result.getWidth(); x++) {
// for (int y = 0; y < result.getHeight(); y++) {
// int p = result.getRGB(x, y);
// p = -p - 1;
// result.setRGB(x, y, p & 0xFFFFFF);
// }
// }
// }
if (pi.inverted) {
result = ImageViewPane.invert(result);
}
return result;
}
public static BufferedImage scale(BufferedImage orig, int maxWidth, int maxHeight) {
BufferedImage result = new BufferedImage(maxWidth, maxHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = result.createGraphics();
AffineTransform transform = ImageViewPane.getAffineTransform(1, 1, 0, false, false, orig, maxWidth, maxHeight);
AffineTransform prev = g.getTransform();
try {
g.setTransform(transform);
g.drawImage(orig, 0, 0, null);
} finally {
g.setTransform(prev);
}
g.dispose();
return result;
}
static BufferedImage createErrorImage(int maxWidth, int maxHeight) {
BufferedImage result = new BufferedImage(maxWidth, maxHeight, BufferedImage.TYPE_INT_ARGB);
Graphics g = result.createGraphics();
try {
g.setColor(Color.RED);
g.setFont(new Font("Sans Serif", Font.BOLD, 36));
g.drawString("E", 20, 60);
g.drawRect(0, 0, maxWidth - 1, maxHeight - 1);
} finally {
g.dispose();
}
return result;
}
private static void exec(List<String> cmd) throws Exception {
if (LOG.isDebugEnabled()) {
LOG.debug("Exec: " + cmd);
}
Process process = Runtime.getRuntime().exec(cmd.toArray(new String[0]));
int r = process.waitFor();
LOG.debug("Result: " + r);
if (r != 0) {
throw new Exception("Error execution " + cmd + ": " + r);
}
}
private static Process execNoWait(String cmd) throws Exception {
LOG.debug("Exec: " + cmd);
return Runtime.getRuntime().exec(cmd);
}
}
| 6,919 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
PdfInsert.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/process/pdf/PdfInsert.java | package org.alex73.skarynka.scan.process.pdf;
import java.text.DecimalFormat;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
public class PdfInsert {
static String IN = "/home/alex/e/in.pdf";
static String OUT = "/home/alex/e/out.pdf";
static float scale = 0.25f;
static PdfDocument pdfDocument;
public static void main(String[] args) throws Exception {
pdfDocument = new PdfDocument(new PdfReader(IN), new PdfWriter(OUT));
Document completeDocument = new Document(pdfDocument);
for (int i = 1; i <= 39; i++) {
addPage("/home/alex/e/" + new DecimalFormat("00").format(i) + ".png.jpg", i + 1);
}
for (int i = 1; i <= pdfDocument.getNumberOfPages(); i++) {
System.out.println(i + " " + pdfDocument.getPage(i).getPageSize());
}
completeDocument.close();
}
static void addPage(String file, int idx) throws Exception {
ImageData imgData = ImageDataFactory.create(file);
Image image = new Image(imgData);
PageSize ps = new PageSize(image.getImageWidth() * scale, image.getImageHeight() * scale);
PdfPage page = pdfDocument.addNewPage(idx, ps);
PdfCanvas canvas = new PdfCanvas(page);
canvas.addImageFittedIntoRectangle(imgData, ps, false);
}
}
| 1,686 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
ExtractImages.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/process/pdf/ExtractImages.java | package org.alex73.skarynka.scan.process.pdf;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Set;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.canvas.parser.EventType;
import com.itextpdf.kernel.pdf.canvas.parser.PdfCanvasProcessor;
import com.itextpdf.kernel.pdf.canvas.parser.data.IEventData;
import com.itextpdf.kernel.pdf.canvas.parser.data.ImageRenderInfo;
import com.itextpdf.kernel.pdf.canvas.parser.listener.IEventListener;
public class ExtractImages {
public static final Path DIR = Paths.get(".");
public static final String OUT = "%06d%s.jpg";
static int outp = 0;
public static void main(String[] args) throws Exception {
Files.find(DIR, 10, (p, a) -> p.getFileName().toString().toLowerCase().endsWith(".pdf")).sorted()
.forEach(p -> process(p));
}
static void process(Path p) {
outp = 0;
try (PdfDocument pdfDoc = new PdfDocument(new PdfReader(p.toFile()))) {
Path dir = Paths.get(p.toString().replaceAll("\\.pdf$", ""));
Files.createDirectories(dir);
int prevp = 0;
for (int i = 1; i <= pdfDoc.getNumberOfPages(); i++) {
final int ii = i;
PdfPage page = pdfDoc.getPage(i);
new PdfCanvasProcessor(new IEventListener() {
String suffix = "";
@Override
public Set<EventType> getSupportedEvents() {
return null;
}
@Override
public void eventOccurred(IEventData data, EventType type) {
if (type == EventType.RENDER_IMAGE) {
if (ii != prevp) {
outp++;
suffix = "";
}
ImageRenderInfo ri = (ImageRenderInfo) data;
byte[] image = ri.getImage().getImageBytes();
try {
Path out = dir.resolve(String.format(OUT, outp, suffix));
Files.write(out, image);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
if (suffix.isEmpty()) {
suffix = "a";
} else {
suffix = Character.toString((char) (suffix.charAt(0) + 1));
}
}
}
}).processPageContent(page);
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
| 2,958 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
PdfCreator.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/process/pdf/PdfCreator.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan.process.pdf;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import org.alex73.skarynka.scan.Book2;
import org.alex73.skarynka.scan.Book2.PageInfo;
import org.alex73.skarynka.scan.process.PageFileInfo;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.geom.AffineTransform;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
public class PdfCreator {
public static void create(File outFile, File[] jpegs) throws Exception {
PdfWriter writer = new PdfWriter(outFile);
PdfDocument pdf = new PdfDocument(writer);
Document doc = new Document(pdf);
for (File jpeg : jpegs) {
ImageData imgData = ImageDataFactory.create(jpeg.toURI().toURL());
Image image = new Image(imgData);
PageSize ps = new PageSize(image.getImageWidth(), image.getImageHeight());
PdfPage page = pdf.addNewPage(ps);
PdfCanvas canvas = new PdfCanvas(page);
canvas.addImageAt(imgData, 0, 0, false);
}
doc.close();
writer.flush();
writer.close();
}
private final PdfWriter writer;
private final PdfDocument pdf;
private final Document doc;
public PdfCreator(File outFile) throws Exception {
writer = new PdfWriter(outFile);
pdf = new PdfDocument(writer);
doc = new Document(pdf);
}
public void addPage(Book2 book, String pageNum) throws Exception {
PageFileInfo fi = new PageFileInfo(book, pageNum);
ImageData imgData = ImageDataFactory.create(fi.getOriginalFile().toURI().toURL());
PageInfo pi = fi.getPageInfo();
if (pi.inverted) {
imgData.setDecode(new float[] { 1, 0, 1, 0, 1, 0, 1, 0 });
}
Image image = new Image(imgData);
float width = pi.rotate % 2 == 0 ? image.getImageWidth() : image.getImageHeight();
float height = pi.rotate % 2 == 0 ? image.getImageHeight() : image.getImageWidth();
PageSize ps = new PageSize(width, height);
PdfPage page = pdf.addNewPage(ps);
PdfCanvas canvas = new PdfCanvas(page);
AffineTransform at = new AffineTransform();
rotate(pi.rotate, at, image);
if (pi.mirrorHorizontal) {
at.scale(-1, 1);
at.translate(-image.getImageWidth(), 0);
}
if (pi.mirrorVertical) {
at.scale(1, -1);
at.translate(0, -image.getImageHeight());
}
canvas.concatMatrix(at);
canvas.addImageAt(imgData, 0, 0, false);
}
public void close() throws Exception {
doc.close();
writer.flush();
writer.close();
}
private void rotate(int rotation, AffineTransform tr, Image image) {
switch (rotation) {
case 0:
break;
case 1:
tr.rotate(Math.PI * 3 / 2);
tr.translate(-image.getImageWidth(), 0);
break;
case 2:
tr.rotate(Math.PI);
tr.translate(-image.getImageWidth(), -image.getImageHeight());
break;
case 3:
tr.rotate(Math.PI / 2);
tr.translate(0, -image.getImageHeight());
break;
default:
throw new RuntimeException("rotation=" + rotation);
}
}
public static void main(String[] args) throws Exception {
Files.find(Paths.get("."), Integer.MAX_VALUE, (p, a) -> {
if (!a.isDirectory()) {
return false;
}
try {
boolean r = Files.list(p).filter(pj -> isJpeg(pj)).findFirst().isPresent();
return r;
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}).sorted().forEach(p -> {
Path pdf = p.getParent().resolve(p.getFileName()+ ".pdf");
if (Files.exists(pdf)) {
return;
}
Path temp = p.getParent().resolve(p.getFileName()+ ".pdf.temp");
File[] jpegs = p.toFile().listFiles(new FileFilter() {
@Override
public boolean accept(File f) {
return isJpeg(f.toPath());
}
});
Arrays.sort(jpegs);
try {
System.out.println(pdf);
create(temp.toFile(), jpegs);
Files.move(temp, pdf);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
});
}
static boolean isJpeg(Path f) {
String fn = f.getFileName().toString().toLowerCase();
return fn.endsWith(".jp2") || fn.endsWith(".jpg") || fn.endsWith(".jpeg");
}
}
| 6,060 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
ExtractImages2.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/process/pdf/ExtractImages2.java | package org.alex73.skarynka.scan.process.pdf;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.canvas.parser.EventType;
import com.itextpdf.kernel.pdf.canvas.parser.PdfCanvasProcessor;
import com.itextpdf.kernel.pdf.canvas.parser.data.IEventData;
import com.itextpdf.kernel.pdf.canvas.parser.data.ImageRenderInfo;
import com.itextpdf.kernel.pdf.canvas.parser.listener.IEventListener;
public class ExtractImages2 {
public static final Path DIR = Paths.get("/home/alex/b/");
public static void main(String[] args) throws Exception {
Files.find(DIR, 10, (p, a) -> p.getFileName().toString().endsWith(".jpg")).sorted().forEach(p -> process(p));
Files.find(DIR, 10, (p, a) -> p.getFileName().toString().endsWith(".pdf")).sorted().forEach(p -> process(p));
}
static final Pattern RE_SH = Pattern
.compile("([0-9]+\\.[0-9]+\\.[0-9]+a?)/сш\\.([0-9]+)/сканирование([0-9]+)\\.pdf");
static final Pattern RE_SH_JPG = Pattern
.compile("([0-9]+\\.[0-9]+\\.[0-9]+a?)/сш\\.([0-9]+)/сканирование([0-9]+)\\.jpg");
static final Pattern RE_SH2 = Pattern.compile("([0-9]+\\.[0-9]+\\.[0-9]+a?)/сканирование([0-9]+)\\.pdf");
static final Pattern RE_T3 = Pattern
.compile("([0-9]+\\.[0-9]+\\.[0-9]+a?)/(T_)?([0-9]+\\.[0-9]+\\.[0-9]+a?)\\.pdf");
static final Pattern RE_T4 = Pattern
.compile("([0-9]+\\.[0-9]+\\.[0-9]+a?)/(T_)?([0-9]+\\.[0-9]+\\.[0-9]+a?+\\.[0-9,]+)\\.pdf");
static Path outDir;
static int pageIndex;
static void process(Path pdf) {
String p = DIR.relativize(pdf).toString().replace(" ", "");
Matcher m;
String dir = null, fn = null, page = null;
if ((m = RE_SH.matcher(p)).matches()) {
dir = m.group(1);
fn = m.group(1) + '.' + m.group(2);
page = m.group(3);
} else if ((m = RE_SH_JPG.matcher(p)).matches()) {
dir = m.group(1);
fn = m.group(1) + '.' + m.group(2);
page = m.group(3);
} else if ((m = RE_SH2.matcher(p)).matches()) {
dir = m.group(1);
fn = m.group(1);
page = m.group(2);
} else if ((m = RE_T3.matcher(p)).matches()) {
dir = m.group(1);
fn = m.group(3);
page = null;
} else if ((m = RE_T4.matcher(p)).matches()) {
dir = m.group(1);
fn = m.group(3);
page = null;
} else {
throw new RuntimeException(p);
}
if (!fn.startsWith(dir)) {
throw new RuntimeException(p);
}
outDir = Paths.get("/data/tmp/2/" + fn);
if (page == null) {
if (Files.isDirectory(outDir)) {
System.out.println("Already exist: " + outDir);
}
}
try {
Files.createDirectories(outDir);
if (p.toString().endsWith(".jpg")) {
pageIndex = Integer.parseInt(page);
Path jpeg = outDir.resolve("page-" + PFMT.format(pageIndex) + ".jpg");
Files.copy(pdf, jpeg);
return;
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
count = 0;
count(pdf);
if (page == null) {
if (count < 3) {
throw new RuntimeException(p);
}
pageIndex = 1;
} else {
if (count != 1) {
throw new RuntimeException(p);
}
pageIndex = Integer.parseInt(page);
}
wr(pdf);
}
static int count;
static void count(Path pdf) {
try (PdfDocument pdfDoc = new PdfDocument(new PdfReader(pdf.toFile()))) {
for (int i = 1; i <= pdfDoc.getNumberOfPages(); i++) {
PdfPage page = pdfDoc.getPage(i);
new PdfCanvasProcessor(new IEventListener() {
@Override
public Set<EventType> getSupportedEvents() {
return null;
}
@Override
public void eventOccurred(IEventData data, EventType type) {
if (type == EventType.RENDER_IMAGE) {
count++;
}
}
}).processPageContent(page);
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
static final DecimalFormat PFMT = new DecimalFormat("0000");
static void wr(Path pdf) {
System.out.println("Parse " + pdf);
try (PdfDocument pdfDoc = new PdfDocument(new PdfReader(pdf.toFile()))) {
for (int i = 1; i <= pdfDoc.getNumberOfPages(); i++) {
PdfPage page = pdfDoc.getPage(i);
new PdfCanvasProcessor(new IEventListener() {
@Override
public Set<EventType> getSupportedEvents() {
return null;
}
@Override
public void eventOccurred(IEventData data, EventType type) {
if (type == EventType.RENDER_IMAGE) {
ImageRenderInfo ri = (ImageRenderInfo) data;
byte[] image = ri.getImage().getImageBytes();
try {
Path jpeg = outDir.resolve("page-" + PFMT.format(pageIndex) + ".jpg");
if (Files.exists(jpeg)) {
throw new RuntimeException(jpeg.toString());
}
pageIndex++;
Files.write(jpeg, image);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
}).processPageContent(page);
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
| 6,487 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
TagsPanel.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/ui/TagsPanel.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan.ui;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionListener;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
* Tags panel widget for display page tags from config.xml.
*
* @author Aleś Bułojčyk <alex73mail@gmail.com>
*/
public class TagsPanel extends JPanel {
public TagsPanel() {
super(new GridBagLayout());
add(new JLabel("tags panel"));
}
public void setup(Map<String, String> tags) {
removeAll();
GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 0, 0, GridBagConstraints.WEST,
GridBagConstraints.HORIZONTAL, new Insets(2, 3, 2, 3), 0, 0);
for (Map.Entry<String, String> en : tags.entrySet()) {
JCheckBox cb = new JCheckBox(en.getValue());
cb.setName(en.getKey());
// cb.addActionListener(actionTag);
add(cb, gbc);
gbc.gridy++;
}
}
public void setValues(Set<String> tags) {
for (int i = 0; i < getComponentCount(); i++) {
JCheckBox cb = (JCheckBox) getComponent(i);
cb.setSelected(tags.contains(cb.getName()));
}
}
public Set<String> getValues() {
Set<String> result = new TreeSet<>();
for (int i = 0; i < getComponentCount(); i++) {
JCheckBox cb = (JCheckBox) getComponent(i);
if (cb.isSelected()) {
result.add(cb.getName());
}
}
return result;
}
public void addActionListener(ActionListener listener) {
for (int i = 0; i < getComponentCount(); i++) {
JCheckBox cb = (JCheckBox) getComponent(i);
cb.addActionListener(listener);
}
}
}
| 2,821 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
ToolsPedalController.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/ui/ToolsPedalController.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan.ui;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import org.alex73.skarynka.scan.DataStorage;
import org.alex73.skarynka.scan.Messages;
import org.alex73.skarynka.scan.hid.HIDScanController;
public class ToolsPedalController {
static ToolsPedal dialog;
static Cleaner cleaner;
static long cleanTime;
public static void show() {
dialog = new ToolsPedal(DataStorage.mainFrame, true);
dialog.setSize(800, 600);
dialog.setLocationRelativeTo(DataStorage.mainFrame);
if (DataStorage.hidScanDevice == null) {
dialog.lblConnected.setText(Messages.getString("TOOLS_PEDAL_NOTDEFINED"));
} else if (!DataStorage.hidScanDevice.isConnected()) {
dialog.lblConnected.setText(Messages.getString("TOOLS_PEDAL_NOTCONNECTED"));
} else {
dialog.lblConnected.setText(
Messages.getString("TOOLS_PEDAL_CONNECTED", DataStorage.hidScanDevice.getHIDDeviceUsbId()));
}
DataStorage.hidScanDevice.setTestListener(hidListener);
dialog.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
cleaner.finished = true;
DataStorage.hidScanDevice.setTestListener(null);
}
});
cleanTime = Long.MAX_VALUE;
cleaner = new Cleaner();
cleaner.start();
dialog.setVisible(true);
}
static HIDScanController.ScanListener hidListener = new HIDScanController.ScanListener() {
@Override
public void pressed(String key) {
dialog.lblKey.setText(dialog.lblKey.getText() + key + "\n");
cleanTime = System.currentTimeMillis() + 3000;
}
};
static class Cleaner extends Thread {
boolean finished;
@Override
public void run() {
try {
while (!finished) {
Thread.sleep(1000);
if (cleanTime < System.currentTimeMillis()) {
dialog.lblKey.setText("");
}
}
} catch (Exception ex) {
}
}
}
}
| 3,148 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
ToolsPedal.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/ui/ToolsPedal.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan.ui;
import org.alex73.skarynka.scan.Messages;
/**
*
* @author alex
*/
public class ToolsPedal extends javax.swing.JDialog {
/**
* Creates new form ToolsPedalTest
*/
public ToolsPedal(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
lblConnected = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
lblKey = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle(Messages.getString("TOOLS_PEDAL_HEADER")); // NOI18N
lblConnected.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N
lblConnected.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblConnected.setText("conn");
getContentPane().add(lblConnected, java.awt.BorderLayout.NORTH);
jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
lblKey.setColumns(20);
lblKey.setFont(new java.awt.Font("Dialog", 0, 36)); // NOI18N
lblKey.setForeground(new java.awt.Color(255, 0, 0));
lblKey.setRows(5);
jScrollPane1.setViewportView(lblKey);
getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ToolsPedal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ToolsPedal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ToolsPedal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ToolsPedal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
ToolsPedal dialog = new ToolsPedal(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
public javax.swing.JScrollPane jScrollPane1;
public javax.swing.JLabel lblConnected;
public javax.swing.JTextArea lblKey;
// End of variables declaration//GEN-END:variables
}
| 5,015 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
MainFrame.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/ui/MainFrame.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan.ui;
import org.alex73.skarynka.scan.Messages;
/**
* @author Aleś Bułojčyk <alex73mail@gmail.com>
*/
public class MainFrame extends javax.swing.JFrame {
/**
* Creates new form MainFrame
*/
public MainFrame() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
viewButtonsGroup = new javax.swing.ButtonGroup();
jPanel1 = new javax.swing.JPanel();
cbProcess = new javax.swing.JCheckBox();
tabs = new javax.swing.JTabbedPane();
jMenuBar1 = new javax.swing.JMenuBar();
workMenu = new javax.swing.JMenu();
processScan = new javax.swing.JMenuItem();
processAdd = new javax.swing.JMenuItem();
closeBook = new javax.swing.JMenuItem();
viewMenu = new javax.swing.JMenu();
viewInc = new javax.swing.JMenuItem();
viewDec = new javax.swing.JMenuItem();
jSeparator2 = new javax.swing.JPopupMenu.Separator();
itemAll = new javax.swing.JRadioButtonMenuItem();
itemSeq = new javax.swing.JRadioButtonMenuItem();
itemCropErr = new javax.swing.JRadioButtonMenuItem();
itemOdd = new javax.swing.JRadioButtonMenuItem();
itemEven = new javax.swing.JRadioButtonMenuItem();
cameraMenu = new javax.swing.JMenu();
cameraInit = new javax.swing.JMenuItem();
cameraFocus = new javax.swing.JMenuItem();
jSeparator1 = new javax.swing.JPopupMenu.Separator();
cameraBadPixels = new javax.swing.JMenuItem();
toolsPedal = new javax.swing.JMenuItem();
toolsMenu = new javax.swing.JMenu();
addAllFiles = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
setTitle(Messages.getString("FRAME_TITLE")); // NOI18N
jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));
cbProcess.setSelected(true);
cbProcess.setText(Messages.getString("PANEL_EDIT_PROCESS")); // NOI18N
jPanel1.add(cbProcess);
getContentPane().add(jPanel1, java.awt.BorderLayout.SOUTH);
getContentPane().add(tabs, java.awt.BorderLayout.CENTER);
workMenu.setText(Messages.getString("MENU_BOOK")); // NOI18N
processScan.setText(Messages.getString("MENU_BOOK_SCAN")); // NOI18N
workMenu.add(processScan);
processAdd.setText(Messages.getString("MENU_BOOK_ADD")); // NOI18N
workMenu.add(processAdd);
closeBook.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_W, java.awt.event.InputEvent.CTRL_MASK));
closeBook.setText(Messages.getString("MENU_BOOK_CLOSE")); // NOI18N
workMenu.add(closeBook);
jMenuBar1.add(workMenu);
viewMenu.setText(Messages.getString("MENU_VIEW")); // NOI18N
viewInc.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ADD, java.awt.event.InputEvent.CTRL_MASK));
viewInc.setText(Messages.getString("MENU_VIEW_INC")); // NOI18N
viewMenu.add(viewInc);
viewDec.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_SUBTRACT, java.awt.event.InputEvent.CTRL_MASK));
viewDec.setText(Messages.getString("MENU_VIEW_DEC")); // NOI18N
viewMenu.add(viewDec);
viewMenu.add(jSeparator2);
viewButtonsGroup.add(itemAll);
itemAll.setSelected(true);
itemAll.setText(Messages.getString("MENU_VIEW_ALL")); // NOI18N
viewMenu.add(itemAll);
viewButtonsGroup.add(itemSeq);
itemSeq.setText(Messages.getString("MENU_VIEW_SEQ")); // NOI18N
viewMenu.add(itemSeq);
viewButtonsGroup.add(itemCropErr);
itemCropErr.setText(Messages.getString("MENU_VIEW_CROP_ERRORS")); // NOI18N
viewMenu.add(itemCropErr);
viewButtonsGroup.add(itemOdd);
itemOdd.setText(Messages.getString("MENU_VIEW_ODD")); // NOI18N
viewMenu.add(itemOdd);
viewButtonsGroup.add(itemEven);
itemEven.setText(Messages.getString("MENU_VIEW_EVEN")); // NOI18N
viewMenu.add(itemEven);
jMenuBar1.add(viewMenu);
cameraMenu.setText(Messages.getString("MENU_DEVICES")); // NOI18N
cameraInit.setText(Messages.getString("MENU_TOOLS_CAMERA_INIT")); // NOI18N
cameraMenu.add(cameraInit);
cameraFocus.setText(Messages.getString("MENU_TOOLS_CAMERA_FOCUS")); // NOI18N
cameraMenu.add(cameraFocus);
cameraMenu.add(jSeparator1);
cameraBadPixels.setText(Messages.getString("MENU_TOOLS_CAMERA_BADPIXELS")); // NOI18N
cameraMenu.add(cameraBadPixels);
toolsPedal.setText(Messages.getString("MENU_TOOLS_PEDAL_TEST")); // NOI18N
cameraMenu.add(toolsPedal);
jMenuBar1.add(cameraMenu);
toolsMenu.setText(Messages.getString("MENU_TOOLS")); // NOI18N
addAllFiles.setText(Messages.getString("MENU_ADD_ALL")); // NOI18N
toolsMenu.add(addAllFiles);
jMenuBar1.add(toolsMenu);
setJMenuBar(jMenuBar1);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
public javax.swing.JMenuItem addAllFiles;
public javax.swing.JMenuItem cameraBadPixels;
public javax.swing.JMenuItem cameraFocus;
public javax.swing.JMenuItem cameraInit;
public javax.swing.JMenu cameraMenu;
public javax.swing.JCheckBox cbProcess;
public javax.swing.JMenuItem closeBook;
public javax.swing.JRadioButtonMenuItem itemAll;
public javax.swing.JRadioButtonMenuItem itemCropErr;
public javax.swing.JRadioButtonMenuItem itemEven;
public javax.swing.JRadioButtonMenuItem itemOdd;
public javax.swing.JRadioButtonMenuItem itemSeq;
public javax.swing.JMenuBar jMenuBar1;
public javax.swing.JPanel jPanel1;
public javax.swing.JPopupMenu.Separator jSeparator1;
public javax.swing.JPopupMenu.Separator jSeparator2;
public javax.swing.JMenuItem processAdd;
public javax.swing.JMenuItem processScan;
public javax.swing.JTabbedPane tabs;
public javax.swing.JMenu toolsMenu;
public javax.swing.JMenuItem toolsPedal;
public javax.swing.ButtonGroup viewButtonsGroup;
public javax.swing.JMenuItem viewDec;
public javax.swing.JMenuItem viewInc;
public javax.swing.JMenu viewMenu;
public javax.swing.JMenu workMenu;
// End of variables declaration//GEN-END:variables
}
| 9,443 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
EditPageController.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/ui/page/EditPageController.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan.ui.page;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.InputMap;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import org.alex73.skarynka.scan.Book2;
import org.alex73.skarynka.scan.Context;
import org.alex73.skarynka.scan.DataStorage;
import org.alex73.skarynka.scan.Messages;
import org.alex73.skarynka.scan.ui.book.PanelEditController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Controller for edit page dialog.
*
* @author Aleś Bułojčyk <alex73mail@gmail.com>
*/
public class EditPageController {
private static Logger LOG = LoggerFactory.getLogger(EditPageController.class);
enum RECT_MODE {
SIZE, POS
};
RECT_MODE currentRectMode;
private EditPageDialog dialog;
private final PanelEditController bookController;
private final Book2 book;
private final List<String> pages;
private String page;
private Dimension fullImageSize;
public EditPageController(PanelEditController bookController, List<String> pages, String currentPageNumber) {
this.bookController=bookController;
this.book=bookController.getBook();
this.pages = pages;
page = Book2.formatPageNumber(currentPageNumber);
Book2.PageInfo pi = book.getPageInfo(page);
dialog = new EditPageDialog(DataStorage.mainFrame, true);
fullImageSize = new Dimension(pi.imageSizeX, pi.imageSizeY);
dialog.btnNext.addActionListener(actionNext);
dialog.btnPrev.addActionListener(actionPrev);
dialog.btnSize.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int c = 0;
for (String page : pages) {
Book2.PageInfo pi = book.getPageInfo(page);
if (pi.cropPosX > 0 && pi.cropPosY > 0) {
c++;
}
}
if (c > 0 && JOptionPane.showConfirmDialog(DataStorage.mainFrame,
Messages.getString("PAGE_NEW_CROP", c), Messages.getString("ERROR_TITLE"),
JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE) != JOptionPane.OK_OPTION) {
return;
}
for (String page : pages) {
Book2.PageInfo pi = book.getPageInfo(page);
pi.cropPosX = -1;
pi.cropPosY = -1;
}
dialog.btnPos.setSelected(false);
currentRectMode = RECT_MODE.SIZE;
}
});
dialog.btnPos.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
currentRectMode = dialog.btnPos.isSelected() ? RECT_MODE.POS : null;
}
});
dialog.btnPosAll.addActionListener((e) -> {
Book2.PageInfo pic = book.getPageInfo(page);
for(String p:pages) {
Book2.PageInfo pis = book.getPageInfo(p);
pis.cropPosX=pic.cropPosX;
pis.cropPosY=pic.cropPosY;
}
});
// dialog.cbColor.addActionListener(actionColor);
// dialog.cbEdit.addActionListener(actionEdit);
dialog.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
bookSave();
bookController.show();
}
});
dialog.tags.setup(Context.getPageTags());
dialog.tags.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Book2.PageInfo pi = book.getPageInfo(page);
pi.tags.clear();
pi.tags.addAll(dialog.tags.getValues());
}
});
addAction(KeyEvent.VK_F1, actionPrev);
addAction(KeyEvent.VK_F2, actionNext);
addAction(KeyEvent.VK_UP, actionUp);
addAction(KeyEvent.VK_DOWN, actionDown);
addAction(KeyEvent.VK_LEFT, actionLeft);
addAction(KeyEvent.VK_RIGHT, actionRight);
addAction(KeyEvent.VK_ESCAPE, actionEsc);
// addAction(KeyEvent.VK_C, actionColor);
// addAction(KeyEvent.VK_E, actionEdit);
dialog.getContentPane().addMouseListener(mouseListener);
dialog.getContentPane().addMouseMotionListener(mouseMotionListener);
showPage();
if (fullImageSize.width == 0 && fullImageSize.height == 0) {
fullImageSize.width = dialog.preview.getImage().getWidth();
fullImageSize.height = dialog.preview.getImage().getHeight();
}
dialog.setSize(1000, 800);
dialog.setLocationRelativeTo(DataStorage.mainFrame);
}
@SuppressWarnings("serial")
Action actionEsc = new AbstractAction("esc") {
@Override
public void actionPerformed(ActionEvent e) {
dialog.dispose();
bookSave();
bookController.show();
}
};
@SuppressWarnings("serial")
Action actionPrev = new AbstractAction("prev") {
@Override
public void actionPerformed(ActionEvent e) {
bookSave();
int pos = pages.indexOf(page);
if (pos >= 0 && pos > 0) {
page = Book2.formatPageNumber(pages.get(pos - 1));
showPage();
}
}
};
@SuppressWarnings("serial")
Action actionNext = new AbstractAction("next") {
@Override
public void actionPerformed(ActionEvent e) {
bookSave();
int pos = pages.indexOf(page);
if (pos >= 0 && pos < pages.size() - 1) {
page = Book2.formatPageNumber(pages.get(pos + 1));
showPage();
}
}
};
@SuppressWarnings("serial")
Action actionUp = new AbstractAction("up") {
@Override
public void actionPerformed(ActionEvent e) {
if (currentRectMode == RECT_MODE.POS && pressedPoint == null) {
moveCrop(0, -16);
}
}
};
@SuppressWarnings("serial")
Action actionDown = new AbstractAction("down") {
@Override
public void actionPerformed(ActionEvent e) {
if (currentRectMode == RECT_MODE.POS && pressedPoint == null) {
moveCrop(0, 16);
}
}
};
@SuppressWarnings("serial")
Action actionLeft = new AbstractAction("left") {
@Override
public void actionPerformed(ActionEvent e) {
if (currentRectMode == RECT_MODE.POS && pressedPoint == null) {
moveCrop(-16, 0);
}
}
};
@SuppressWarnings("serial")
Action actionRight = new AbstractAction("right") {
@Override
public void actionPerformed(ActionEvent e) {
if (currentRectMode == RECT_MODE.POS && pressedPoint == null) {
moveCrop(16, 0);
}
}
};
@SuppressWarnings("serial")
Action actionTag = new AbstractAction("tag") {
@Override
public void actionPerformed(ActionEvent e) {
// if (e.getSource() != dialog.cbColor) {
// dialog.cbColor.setSelected(!dialog.cbColor.isSelected());
// }
Book2.PageInfo pi = book.getPageInfo(page);
JCheckBox cb = (JCheckBox) e.getSource();
if (cb.isSelected()) {
pi.tags.add(cb.getName());
} else {
pi.tags.remove(cb.getName());
}
}
};
// @SuppressWarnings("serial")
// Action actionEdit = new AbstractAction("edit") {
// @Override
// public void actionPerformed(ActionEvent e) {
// if (e.getSource() != dialog.cbEdit) {
// dialog.cbEdit.setSelected(!dialog.cbEdit.isSelected());
// }
// Book2.PageInfo pi = book.getPageInfo(page);
// pi.needEdit = dialog.cbEdit.isSelected();
// }
// };
void moveCrop(int dx, int dy) {
int ddx = 0, ddy = 0;
switch (dialog.preview.getRotation()) {
case 0:
ddx = dx;
ddy = dy;
break;
case 1:
ddx = dy;
ddy = -dx;
break;
case 2:
ddx = -dx;
ddy = -dy;
break;
case 3:
ddx = -dy;
ddy = dx;
break;
}
Book2.PageInfo pi = book.getPageInfo(page);
pi.cropPosX += ddx;
pi.cropPosY += ddy;
dialog.preview.getCrops().clear();
dialog.preview.getCrops().add(dialog.preview
.screen2image(new Rectangle(pi.cropPosX, pi.cropPosY, book.cropSizeX, book.cropSizeY), fullImageSize));
dialog.preview.repaint();
}
public static void show(PanelEditController bookController, List<String> pages, String page) {
new EditPageController(bookController, pages, page).dialog.setVisible(true);
}
void showPage() {
try {
dialog.pageLabel.setText(Messages.getString("PAGE_NUMBER", Book2.simplifyPageNumber(page)));
dialog.btnNext.setEnabled(pages.size() > 0 && !pages.get(pages.size() - 1).equals(this.page));
dialog.btnPrev.setEnabled(pages.size() > 0 && !pages.get(0).equals(this.page));
Book2.PageInfo pi = book.getPageInfo(page);
fullImageSize = new Dimension(pi.imageSizeX, pi.imageSizeY);
if (pi.cropPosX < 0 && pi.cropPosY < 0) {
// not defined yet
String prevPage = Book2.incPage(page, -book.pageStep);
if (!prevPage.isEmpty()) {
Book2.PageInfo piPrev = book.getPageInfo(prevPage);
if (piPrev != null && piPrev.cropPosX >= 0 && piPrev.cropPosY >= 0) {
pi.cropPosX = piPrev.cropPosX;
pi.cropPosY = piPrev.cropPosY;
}
}
}
dialog.preview.setRotation(pi.rotate);
dialog.preview.getCrops().clear();
dialog.preview.getCrops().add(dialog.preview.screen2image(
new Rectangle(pi.cropPosX, pi.cropPosY, book.cropSizeX, book.cropSizeY), fullImageSize));
dialog.preview.displayImage(book.getImage(page), 1, 1);
dialog.tags.setValues(pi.tags);
dialog.errLabel.setText(" ");
} catch (Exception ex) {
LOG.warn("Error open image", ex);
dialog.errLabel
.setText(Messages.getString("ERROR_READ_JPEG", ex.getClass().getName(), ex.getMessage()));
}
}
void bookSave() {
try {
book.save();
} catch (Exception ex) {
LOG.warn("Error book save", ex);
JOptionPane.showMessageDialog(dialog,
Messages.getString("ERROR_BOOK_SAVE", book.getName(), ex.getMessage()),
Messages.getString("ERROR_TITLE"), JOptionPane.ERROR_MESSAGE);
}
}
Point currentPoint, pressedPoint;
MouseListener mouseListener = new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
if (currentRectMode == null) {
return;
}
currentPoint = dialog.preview.mouseToImage(e.getPoint(), dialog.preview.getX(), dialog.preview.getY(),
fullImageSize);
if (LOG.isTraceEnabled()) {
LOG.trace("Mouse release " + e.getPoint() + " / " + currentPoint);
}
Rectangle cropRect = updateRect();
if (currentRectMode == RECT_MODE.SIZE) {
book.cropSizeX = cropRect.width;
book.cropSizeY = cropRect.height;
Book2.PageInfo pi = book.getPageInfo(page);
pi.cropPosX = cropRect.x;
pi.cropPosY = cropRect.y;
currentRectMode = null;
dialog.btnSize.getModel().setSelected(false);
} else if (currentRectMode == RECT_MODE.POS) {
Book2.PageInfo pi = book.getPageInfo(page);
pi.cropPosX = cropRect.x;
pi.cropPosY = cropRect.y;
}
bookSave();
pressedPoint = null;
currentPoint = null;
}
public void mousePressed(MouseEvent e) {
if (currentRectMode == null) {
return;
}
currentPoint = dialog.preview.mouseToImage(e.getPoint(), dialog.preview.getX(), dialog.preview.getY(),
fullImageSize);
if (LOG.isTraceEnabled()) {
LOG.trace("Mouse press " + e.getPoint() + " / " + currentPoint);
}
if (currentRectMode == RECT_MODE.SIZE) {
pressedPoint = currentPoint;
} else if (currentRectMode == RECT_MODE.POS) {
Book2.PageInfo pi = book.getPageInfo(page);
pressedPoint = new Point(currentPoint.x - pi.cropPosX, currentPoint.y - pi.cropPosY);
}
updateRect();
}
};
MouseMotionListener mouseMotionListener = new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
if (pressedPoint != null) {
currentPoint = dialog.preview.mouseToImage(e.getPoint(), dialog.preview.getX(), dialog.preview.getY(),
fullImageSize);
if (LOG.isTraceEnabled()) {
LOG.trace("Mouse drag " + e.getPoint() + " / " + currentPoint);
}
updateRect();
}
}
public void mouseMoved(MouseEvent e) {
if (pressedPoint != null) {
currentPoint = dialog.preview.mouseToImage(e.getPoint(), dialog.preview.getX(), dialog.preview.getY(),
fullImageSize);
if (LOG.isTraceEnabled()) {
LOG.trace("Mouse move " + e.getPoint() + " / " + currentPoint);
}
updateRect();
}
}
};
Rectangle updateRect() {
Rectangle rc = new Rectangle();
if (currentRectMode == RECT_MODE.SIZE) {
rc.x = pressedPoint.x;
rc.y = pressedPoint.y;
rc.width = currentPoint.x - pressedPoint.x;
rc.height = currentPoint.y - pressedPoint.y;
if (rc.width < 0) {
rc.width = -rc.width;
rc.x -= rc.width;
}
if (rc.height < 0) {
rc.height = -rc.height;
rc.y -= rc.height;
}
} else {
rc.x = currentPoint.x - pressedPoint.x;
rc.y = currentPoint.y - pressedPoint.y;
rc.width = book.cropSizeX;
rc.height = book.cropSizeY;
}
dialog.preview.getCrops().clear();
dialog.preview.getCrops().add(dialog.preview.screen2image(rc, fullImageSize));
if (LOG.isTraceEnabled()) {
LOG.trace("Draw crop " + rc);
}
dialog.preview.repaint();
return rc;
}
void addAction(int keyCode, Action action) {
InputMap im = dialog.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
im.put(KeyStroke.getKeyStroke(keyCode, 0), action.getValue(Action.NAME));
dialog.getRootPane().getActionMap().put(action.getValue(Action.NAME), action);
}
}
| 16,979 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
EditPageDialog.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/ui/page/EditPageDialog.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan.ui.page;
import org.alex73.skarynka.scan.Messages;
/**
*@author Aleś Bułojčyk <alex73mail@gmail.com>
*/
public class EditPageDialog extends javax.swing.JDialog {
/**
* Creates new form EditPageDialog
*/
public EditPageDialog(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
btnSize = new javax.swing.JToggleButton();
btnPos = new javax.swing.JToggleButton();
btnPosAll = new javax.swing.JButton();
preview = new org.alex73.skarynka.scan.common.ImageViewPane();
btnPrev = new javax.swing.JButton();
btnNext = new javax.swing.JButton();
errLabel = new javax.swing.JLabel();
pageLabel = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
tags = new org.alex73.skarynka.scan.ui.TagsPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle(Messages.getString("PAGE_TITLE")); // NOI18N
getContentPane().setLayout(new java.awt.GridBagLayout());
btnSize.setText(Messages.getString("PAGE_SIZE")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
getContentPane().add(btnSize, gridBagConstraints);
btnPos.setText(Messages.getString("PAGE_POSITION")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
getContentPane().add(btnPos, gridBagConstraints);
btnPosAll.setText(Messages.getString("PAGE_SET_POS_FOR_ALL")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
getContentPane().add(btnPosAll, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridheight = 20;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(20, 20, 0, 20);
getContentPane().add(preview, gridBagConstraints);
btnPrev.setText(Messages.getString("PAGE_PREV")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 19;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
getContentPane().add(btnPrev, gridBagConstraints);
btnNext.setText(Messages.getString("PAGE_NEXT")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 19;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
getContentPane().add(btnNext, gridBagConstraints);
errLabel.setForeground(new java.awt.Color(255, 0, 0));
errLabel.setText(" ");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 21;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
getContentPane().add(errLabel, gridBagConstraints);
pageLabel.setText(Messages.getString("PAGE_NUMBER")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 18;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
getContentPane().add(pageLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 17;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 1.0;
getContentPane().add(jPanel1, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 15;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
getContentPane().add(tags, gridBagConstraints);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(EditPageDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(EditPageDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(EditPageDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(EditPageDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
EditPageDialog dialog = new EditPageDialog(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
public javax.swing.JButton btnNext;
public javax.swing.JToggleButton btnPos;
public javax.swing.JButton btnPosAll;
public javax.swing.JButton btnPrev;
public javax.swing.JToggleButton btnSize;
public javax.swing.JLabel errLabel;
public javax.swing.JPanel jPanel1;
public javax.swing.JLabel pageLabel;
public org.alex73.skarynka.scan.common.ImageViewPane preview;
public org.alex73.skarynka.scan.ui.TagsPanel tags;
// End of variables declaration//GEN-END:variables
}
| 8,894 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
AddController.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/ui/add/AddController.java | package org.alex73.skarynka.scan.ui.add;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.regex.Matcher;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.RootPaneContainer;
import javax.swing.SwingWorker;
import javax.swing.filechooser.FileFilter;
import org.alex73.skarynka.scan.Book2;
import org.alex73.skarynka.scan.Context;
import org.alex73.skarynka.scan.DataStorage;
import org.alex73.skarynka.scan.Messages;
import org.alex73.skarynka.scan.process.PageFileInfo;
import org.alex73.skarynka.scan.process.ProcessDaemon;
import org.alex73.skarynka.scan.ui.book.PanelEditController;
import org.apache.commons.io.FileUtils;
public class AddController {
private static File currentDir = new File(Context.getBookDir());
// add all new books and image files
public static void addAll() {
LongProcessAllBooks process = new LongProcessAllBooks();
process.execute();
process.showDialog();
DataStorage.refreshBookPanels(false);
DataStorage.activateTab(0);
}
// add image file into one book only
public static void add(PanelEditController panelController) {
final JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setMultiSelectionEnabled(true);
fc.setCurrentDirectory(currentDir);
fc.addChoosableFileFilter(new FileFilter() {
@Override
public String getDescription() {
return Messages.getString("ADD_FILTER_IMAGES");
}
@Override
public boolean accept(File pathname) {
if (pathname.isDirectory()) {
return true;
}
return Book2.IMAGE_FILE.matcher(pathname.getName()).matches();
}
});
fc.setAcceptAllFileFilterUsed(false);
int returnVal = fc.showOpenDialog(DataStorage.mainFrame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
currentDir = fc.getCurrentDirectory();
LongProcess process = new LongProcess(panelController, fc.getSelectedFiles());
process.execute();
process.showDialog();
}
}
/** Show glass pane. */
protected static void showGlassPane() {
((RootPaneContainer) DataStorage.mainFrame).getGlassPane().setVisible(true);
}
/** Hide glass pane. */
protected static void hideGlassPane() {
((RootPaneContainer) DataStorage.mainFrame).getGlassPane().setVisible(false);
}
abstract static class ProcessPages extends SwingWorker<Void, Void> {
protected final AddPages dialog;
private boolean stop;
public ProcessPages() {
dialog = new AddPages(DataStorage.mainFrame, true);
dialog.btnCancel.addActionListener(e -> {
stop = true;
});
dialog.setLocationRelativeTo(DataStorage.mainFrame);
}
protected void addPagesToBook(Book2 book, File[] files) throws Exception {
String nextPage;
List<String> ps = book.listPages();
if (ps.isEmpty()) {
nextPage = Book2.formatPageNumber("1");
} else {
nextPage = Book2.incPage(Book2.simplifyPageNumber(ps.get(ps.size() - 1)), 1);
}
String[] pages = new String[files.length];
for (int i = 0; i < files.length; i++) {
pages[i] = nextPage;
nextPage = Book2.incPage(nextPage, 1);
}
for (int i = 0; i < files.length; i++) {
String fn = files[i].getName();
String ext = fn.substring(fn.lastIndexOf('.') + 1).toLowerCase();
File fo = new File(book.getBookDir(), pages[i] + '.' + ext);
if (fo.exists()) {
throw new Exception("File " + fo + " already exist !");
}
}
for (int i = 0; i < files.length; i++) {
if (stop) {
throw new InterruptedException("Спынена");
}
String fn = files[i].getName();
dialog.text.setText(Messages.getString("DIALOG_ADDPAGE_TEXT", fn));
String ext = fn.substring(fn.lastIndexOf('.') + 1).toLowerCase();
File fo = new File(book.getBookDir(), pages[i] + '.' + ext);
try {
FileUtils.moveFile(files[i], fo);
} catch (Exception ex) {
throw new Exception("Error rename " + files[i] + " to " + fo + " !");
}
ProcessDaemon.updatePageSize(book, pages[i]);
Book2.PageInfo pi = book.new PageInfo(pages[i]);
pi.pageOriginalFileExt = ext;
book.addPage(pi);
ProcessDaemon.createPreviewIfNeed(book, pages[i]);
dialog.progress.setValue(i + 1);
book.save();
}
}
}
/**
* SwingWorker extension for controllers.
*/
public static class LongProcessAllBooks extends ProcessPages {
boolean empty;
public void showDialog() {
dialog.setVisible(true);
}
@Override
protected Void doInBackground() throws Exception {
File[] dirs = new File(Context.getBookDir()).listFiles(new java.io.FileFilter() {
public boolean accept(File p) {
return p.isDirectory();
}
});
List<Book2> books = new ArrayList<>();
List<List<String>> bookFiles = new ArrayList<>();
int totalNewPagesCount = 0;
for (File d : dirs) {
Book2 book = DataStorage.openBook(d.getName(), false);
List<String> newPageFiles = new ArrayList<>();
for (File f : d.listFiles()) {
if (f.isDirectory()) {
continue;
}
Matcher m = Book2.RE_PAGE_IMAGE_FILE.matcher(f.getName());
if (m.matches()) {
Book2.PageInfo pi = book.getPageInfo(m.group(1));
if (pi == null) {
throw new Exception("No page in book " + d.getName() + " from file: " + f.getName());
}
if (!new PageFileInfo(book, m.group(1)).getOriginalFile().getName().equals(f.getName())) {
throw new Exception(
"Wrong page extension in book " + d.getName() + " for file: " + f.getName());
}
} else {
String ext = f.getName().substring(f.getName().lastIndexOf('.') + 1).toLowerCase();
for (String te : Book2.IMAGE_EXTENSIONS) {
if (ext.equals(te)) {
newPageFiles.add(f.getName());
break;
}
}
}
}
if (!newPageFiles.isEmpty()) {
Collections.sort(newPageFiles);
books.add(book);
bookFiles.add(newPageFiles);
totalNewPagesCount += newPageFiles.size();
}
}
empty = books.isEmpty();
dialog.progress.setMaximum(totalNewPagesCount);
dialog.progress.setValue(0);
for (int i = 0; i < books.size(); i++) {
Book2 b = books.get(i);
List<String> newPageFiles = bookFiles.get(i);
File[] files = new File[newPageFiles.size()];
for (int j = 0; j < files.length; j++) {
files[j] = new File(b.getBookDir(), newPageFiles.get(j));
}
addPagesToBook(b, files);
}
return null;
}
@Override
protected void done() {
try {
get();
if (empty) {
JOptionPane.showMessageDialog(DataStorage.mainFrame, "Няма файлаў для імпарту", "Дадаць файлы",
JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(DataStorage.mainFrame, "Усе файлы імпартаваныя", "Дадаць файлы",
JOptionPane.INFORMATION_MESSAGE);
}
} catch (InterruptedException ex) {
JOptionPane.showMessageDialog(DataStorage.mainFrame, "Interrupted: " + ex.getMessage(), "Памылка",
JOptionPane.ERROR_MESSAGE);
} catch (ExecutionException e) {
Throwable ex = e.getCause();
ex.printStackTrace();
JOptionPane.showMessageDialog(DataStorage.mainFrame, "Error: " + ex.getMessage(), "Памылка",
JOptionPane.ERROR_MESSAGE);
}
dialog.dispose();
}
}
/**
* SwingWorker extension for controllers.
*/
public static class LongProcess extends ProcessPages {
private final PanelEditController panelController;
private final File[] files;
public LongProcess(PanelEditController panelController, File[] files) {
this.panelController = panelController;
this.files = files;
}
public void showDialog() {
dialog.setVisible(true);
}
@Override
protected Void doInBackground() throws Exception {
dialog.progress.setMaximum(files.length);
dialog.progress.setValue(0);
addPagesToBook(panelController.getBook(), files);
return null;
}
@Override
protected void done() {
try {
get();
JOptionPane.showMessageDialog(DataStorage.mainFrame, "Файлы імпартаваныя", "Дадаць файлы",
JOptionPane.INFORMATION_MESSAGE);
} catch (InterruptedException ex) {
JOptionPane.showMessageDialog(DataStorage.mainFrame, "Interrupted: " + ex.getMessage(), "Памылка",
JOptionPane.ERROR_MESSAGE);
} catch (ExecutionException e) {
Throwable ex = e.getCause();
ex.printStackTrace();
JOptionPane.showMessageDialog(DataStorage.mainFrame, "Error: " + ex.getMessage(), "Памылка",
JOptionPane.ERROR_MESSAGE);
}
dialog.dispose();
panelController.show();
}
}
}
| 10,966 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
AddPages.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/ui/add/AddPages.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.alex73.skarynka.scan.ui.add;
import org.alex73.skarynka.scan.Messages;
/**
*
* @author alex
*/
public class AddPages extends javax.swing.JDialog {
/**
* Creates new form AddPages
*/
public AddPages(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
text = new javax.swing.JLabel();
progress = new javax.swing.JProgressBar();
btnCancel = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
setTitle(Messages.getString("DIALOG_ADDPAGE_TITLE")); // NOI18N
setResizable(false);
getContentPane().setLayout(new java.awt.GridBagLayout());
text.setText(Messages.getString("DIALOG_ADDPAGE_TEXT")); // NOI18N
text.setPreferredSize(new java.awt.Dimension(600, 100));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
getContentPane().add(text, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
getContentPane().add(progress, gridBagConstraints);
btnCancel.setText(Messages.getString("DIALOG_ADDPAGE_CANCEL")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
getContentPane().add(btnCancel, gridBagConstraints);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(AddPages.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AddPages.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AddPages.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AddPages.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
AddPages dialog = new AddPages(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
public javax.swing.JButton btnCancel;
public javax.swing.JProgressBar progress;
public javax.swing.JLabel text;
// End of variables declaration//GEN-END:variables
}
| 4,862 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
BooksController.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/ui/book/BooksController.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan.ui.book;
import java.awt.Component;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import org.alex73.skarynka.scan.ActionErrorListener;
import org.alex73.skarynka.scan.Book2;
import org.alex73.skarynka.scan.Context;
import org.alex73.skarynka.scan.DataStorage;
import org.alex73.skarynka.scan.IBookIterator;
import org.alex73.skarynka.scan.ITabController;
import org.alex73.skarynka.scan.Messages;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Controller for books list panel.
*
* @author Aleś Bułojčyk <alex73mail@gmail.com>
*/
public class BooksController implements ITabController {
private static Logger LOG = LoggerFactory.getLogger(BooksController.class);
private BooksPanel panel;
private List<BookRow> books = new ArrayList<>();
private Set<String> currentBooksNames = new HashSet<>();
@Override
public String getTabName() {
return Messages.getString("PANEL_BOOK_TITLE");
}
@Override
public Component getTabComponent() {
return panel;
}
@Override
public void activate() {
DataStorage.mainFrame.workMenu.setEnabled(false);
DataStorage.mainFrame.viewMenu.setEnabled(false);
refresh();
}
@Override
public void deactivate() {
}
@Override
public void close() {
}
public void refresh() {
int selected = panel.table.getSelectedRow();
try {
listScanDirs();
} catch (Throwable ex) {
LOG.error("Error list books", ex);
JOptionPane.showMessageDialog(DataStorage.mainFrame,
"Error: " + ex.getClass() + " / " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
((AbstractTableModel) panel.table.getModel()).fireTableDataChanged();
if (selected >= 0) {
panel.table.setRowSelectionInterval(selected, selected);
}
}
public BooksController() {
try {
panel = new BooksPanel();
((AbstractDocument) panel.txtNewName.getDocument()).setDocumentFilter(bookNameFilter);
listScanDirs();
panel.table.setModel(model());
panel.table.setRowSelectionAllowed(true);
panel.table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) {
BookRow b = books.get(panel.table.getSelectedRow());
DataStorage.openBook(b.bookName, true);
}
}
@Override
public void mousePressed(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
for (int i = 0; i < panel.menuProcess.getComponentCount(); i++) {
Component item = panel.menuProcess.getComponent(i);
if ((item instanceof JMenuItem) && (item.getName() != null)) {
panel.menuProcess.remove(i);
i--;
}
}
if (Context.getPermissions().BookControl) {
for (int scale : new int[] { 25, 50, 75, 100, 200 }) {
JMenuItem item = new JMenuItem(scale + "%");
item.setName(scale + "%");
item.addActionListener(new ChangeScale(scale));
panel.menuProcess.add(item);
}
}
currentBooksNames.clear();
int[] selected = panel.table.getSelectedRows();
boolean allLocals = true;
boolean processAllowed = Context.getPermissions().BookControl;
for (int row : selected) {
BookRow b = books.get(panel.table.convertRowIndexToModel(row));
currentBooksNames.add(b.bookName);
if (!b.local) {
allLocals = false;
}
}
panel.itemFinish.setVisible(allLocals);
if (processAllowed) {
for (Map.Entry<String, String> en : Context.getProcessCommands().entrySet()) {
JMenuItem item = new JMenuItem(en.getValue());
item.setName(en.getKey());
item.addActionListener(commandListener);
panel.menuProcess.add(item);
}
}
panel.menuProcess.show(panel.table, e.getX(), e.getY());
}
}
});
panel.btnCreate.setEnabled(false);
panel.btnCreate.addActionListener(
new ActionErrorListener(panel, "ERROR_BOOK_CREATE", LOG, "Error create book") {
protected void action(ActionEvent e) throws Exception {
File bookDir = new File(Context.getBookDir(), panel.txtNewName.getText());
if (bookDir.exists()) {
JOptionPane.showMessageDialog(panel,
Messages.getString("PANEL_BOOK_NEW_BOOK_EXIST"),
Messages.getString("PANEL_BOOK_TITLE"), JOptionPane.WARNING_MESSAGE);
return;
}
DataStorage.openBook(panel.txtNewName.getText(), true);
}
});
setMenuListeners();
} catch (Throwable ex) {
LOG.error("Error list books", ex);
JOptionPane.showMessageDialog(DataStorage.mainFrame,
"Error: " + ex.getClass() + " / " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
ActionListener commandListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String command = ((JMenuItem) e.getSource()).getName();
DataStorage.iterateByBooks(currentBooksNames, new IBookIterator() {
@Override
public void onBook(Book2 currentBook) throws Exception {
try {
File done = new File(currentBook.getBookDir(), ".process.done");
if (done.exists() && !done.delete()) {
throw new Exception("Error delete .done file");
}
File errors = new File(currentBook.getBookDir(), ".errors");
if (errors.exists() && !errors.delete()) {
throw new Exception("Error delete .errors file");
}
FileUtils.writeStringToFile(new File(currentBook.getBookDir(), ".process"), command,
"UTF-8");
} catch (Throwable ex) {
LOG.error("Error set comand to book", ex);
JOptionPane.showMessageDialog(DataStorage.mainFrame,
"Error: " + ex.getClass() + " / " + ex.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
}
}
});
refresh();
}
};
class ChangeScale implements ActionListener {
private final int scale;
public ChangeScale(int scale) {
this.scale = scale;
}
@Override
public void actionPerformed(ActionEvent e) {
DataStorage.iterateByBooks(currentBooksNames, new IBookIterator() {
@Override
public void onBook(Book2 currentBook) throws Exception {
try {
currentBook.scale = scale;
currentBook.save();
} catch (Throwable ex) {
LOG.error("Error set scale to book", ex);
JOptionPane.showMessageDialog(DataStorage.mainFrame,
"Error: " + ex.getClass() + " / " + ex.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
}
}
});
refresh();
}
};
void setMenuListeners() {
panel.itemFinish.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
DataStorage.iterateByBooks(currentBooksNames, new IBookIterator() {
@Override
public void onBook(Book2 currentBook) throws Exception {
new File(currentBook.getBookDir(), ".local").delete();
currentBook.local = false;
try {
currentBook.save();
} catch (Exception ex) {
LOG.error("Error save book '" + currentBook.getName() + "'", ex);
JOptionPane.showMessageDialog(DataStorage.mainFrame,
Messages.getString("ERROR_BOOK_SAVE", currentBook.getName(),
ex.getMessage()),
Messages.getString("ERROR_TITLE"), JOptionPane.ERROR_MESSAGE);
}
}
});
panel.table.repaint();
}
});
// panel.itemEdit.addActionListener(new ActionListener() {
// @Override
// public void actionPerformed(ActionEvent e) {
// try {
// z
// } catch (Exception ex) {
// LOG.error("Error save book '" + currentBook.getName() + "'", ex);
// JOptionPane.showMessageDialog(DataStorage.mainFrame,
// Messages.getString("ERROR_BOOK_SAVE", currentBook.getName(), ex.getMessage()),
// Messages.getString("ERROR_TITLE"), JOptionPane.ERROR_MESSAGE);
// }
// }
// });
}
TableModel model() {
return new DefaultTableModel() {
@Override
public int getColumnCount() {
return Context.getPermissions().BookControl ? 4 : 3;
}
@Override
public int getRowCount() {
return books.size();
}
@Override
public String getColumnName(int column) {
switch (column) {
case 0:
return Messages.getString("PANEL_BOOK_TABLE_NAME");
case 1:
return Messages.getString("PANEL_BOOK_TABLE_PAGES");
case 2:
return Messages.getString("PANEL_BOOK_TABLE_PAGE_SIZE");
case 3:
return Messages.getString("PANEL_BOOK_TABLE_STATUS");
}
return null;
}
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
@Override
public Object getValueAt(int row, int column) {
BookRow b = books.get(row);
switch (column) {
case 0:
return b.bookName;
case 1:
return b.pagesCount;
case 2:
return b.info;
case 3:
return b.status;
}
return null;
}
};
}
public void listScanDirs() throws Exception {
books.clear();
DataStorage.iterateByBooks(null, new IBookIterator() {
@Override
public void onBook(Book2 book) throws Exception {
if (Context.getPermissions().ShowNonLocalBooks) {
books.add(new BookRow(book));
} else {
if (book.local) {
books.add(new BookRow(book));
}
}
}
});
}
static final Pattern RE_NAME = Pattern.compile("[A-Za-z0-9_\\-\\.]+");
DocumentFilter bookNameFilter = new DocumentFilter() {
protected String check(String data) {
return RE_NAME.matcher(data).matches() ? data : null;
}
@Override
public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
super.remove(fb, offset, length);
update(fb);
}
@Override
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
throws BadLocationException {
string = check(string);
if (string != null) {
super.insertString(fb, offset, string, attr);
update(fb);
} else {
Toolkit.getDefaultToolkit().beep();
}
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
throws BadLocationException {
text = check(text);
if (text != null) {
super.replace(fb, offset, length, text, attrs);
update(fb);
} else {
Toolkit.getDefaultToolkit().beep();
}
}
void update(FilterBypass fb) {
panel.btnCreate.setEnabled(fb.getDocument().getLength() > 0);
}
};
}
| 15,547 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
PageNumber.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/ui/book/PageNumber.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan.ui.book;
import org.alex73.skarynka.scan.Messages;
/**
*
* @author Aleś Bułojčyk <alex73mail@gmail.com>
*/
public class PageNumber extends javax.swing.JDialog {
/**
* Creates new form PageNumber
*/
public PageNumber(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
jLabel1 = new javax.swing.JLabel();
txtNumber = new javax.swing.JTextField();
statusLabel = new javax.swing.JLabel();
renameButton = new javax.swing.JButton();
cbInversed = new javax.swing.JCheckBox();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle(Messages.getString("PAGE_NUMBER_TITLE")); // NOI18N
getContentPane().setLayout(new java.awt.GridBagLayout());
jLabel1.setText(Messages.getString("PAGE_NUMBER_PROMPT")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
getContentPane().add(jLabel1, gridBagConstraints);
txtNumber.setColumns(10);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
getContentPane().add(txtNumber, gridBagConstraints);
statusLabel.setForeground(new java.awt.Color(255, 0, 0));
statusLabel.setText(" error ");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
getContentPane().add(statusLabel, gridBagConstraints);
renameButton.setText(Messages.getString("PAGE_NUMBER_BUTTON")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
getContentPane().add(renameButton, gridBagConstraints);
cbInversed.setText(Messages.getString("PAGE_NUMBER_INVERSED")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
getContentPane().add(cbInversed, gridBagConstraints);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(PageNumber.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(PageNumber.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(PageNumber.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(PageNumber.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
PageNumber dialog = new PageNumber(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
public javax.swing.JCheckBox cbInversed;
public javax.swing.JLabel jLabel1;
public javax.swing.JButton renameButton;
public javax.swing.JLabel statusLabel;
public javax.swing.JTextField txtNumber;
// End of variables declaration//GEN-END:variables
}
| 6,523 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
PagePopupMenu.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/ui/book/PagePopupMenu.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan.ui.book;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JSeparator;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import org.alex73.skarynka.scan.Book2;
import org.alex73.skarynka.scan.Context;
import org.alex73.skarynka.scan.Book2.PageInfo;
import org.alex73.skarynka.scan.ui.page.EditPageController;
import org.alex73.skarynka.scan.DataStorage;
import org.alex73.skarynka.scan.Messages;
import org.alex73.skarynka.scan.process.PageFileInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Popup menu for books list panel.
*
* @author Aleś Bułojčyk <alex73mail@gmail.com>
*/
@SuppressWarnings("serial")
public class PagePopupMenu extends JPopupMenu {
private static Logger LOG = LoggerFactory.getLogger(PagePopupMenu.class);
private final PanelEditController controller;
private final Book2 book;
private List<Integer> selectedIndexes;
private List<String> selectedPages;
// private final String startSelection, endSelection;
public PagePopupMenu(PanelEditController controller) {
this.controller = controller;
this.book = controller.getBook();
selectedIndexes = controller.selection.getSelected();
selectedPages = new ArrayList<>();
for (int p : selectedIndexes) {
selectedPages.add(controller.getPageByIndex(p));
}
JMenuItem remove;
if (selectedIndexes.size() == 1) {
remove = new JMenuItem(Messages.getString("PAGE_POPUP_REMOVE",
Book2.simplifyPageNumber(controller.getPageByIndex(selectedIndexes.get(0)))));
} else {
remove = new JMenuItem(Messages.getString("PAGE_POPUP_REMOVES", selectedIndexes.size()));
}
JMenuItem m1 = new JMenuItem(Messages.getString("PAGE_POPUP_CHANGE_M1"));
JMenuItem p1 = new JMenuItem(Messages.getString("PAGE_POPUP_CHANGE_P1"));
JMenuItem ma = new JMenuItem(Messages.getString("PAGE_POPUP_CHANGE_MA"));
JMenuItem pa = new JMenuItem(Messages.getString("PAGE_POPUP_CHANGE_PA"));
JMenuItem m2 = new JMenuItem(Messages.getString("PAGE_POPUP_CHANGE_M2"));
JMenuItem p2 = new JMenuItem(Messages.getString("PAGE_POPUP_CHANGE_P2"));
JMenuItem mb = new JMenuItem(Messages.getString("PAGE_POPUP_CHANGE_MB"));
JMenuItem pb = new JMenuItem(Messages.getString("PAGE_POPUP_CHANGE_PB"));
JMenuItem editSelected = new JMenuItem(Messages.getString("PAGE_POPUP_EDIT_SELECTED"));
editSelected.addActionListener(editSelectedAction);
JMenuItem rotateLeft = new JMenuItem(Messages.getString("PAGE_POPUP_ROTATE_LEFT"));
rotateLeft.addActionListener(rotateLeftAction);
JMenuItem rotateRight = new JMenuItem(Messages.getString("PAGE_POPUP_ROTATE_RIGHT"));
rotateRight.addActionListener(rotateRightAction);
JMenuItem mirrorHorizontal = new JMenuItem(Messages.getString("PAGE_POPUP_MIRROR_HORIZONTAL"));
mirrorHorizontal.addActionListener(mirrorHorizontalAction);
JMenuItem mirrorVertical = new JMenuItem(Messages.getString("PAGE_POPUP_MIRROR_VERTICAL"));
mirrorVertical.addActionListener(mirrorVerticalAction);
JMenuItem inverted = new JMenuItem(Messages.getString("PAGE_POPUP_INVERTED"));
inverted.addActionListener(invertedAction);
JMenuItem rename = new JMenuItem(Messages.getString("PAGE_POPUP_RENAME"));
rename.addActionListener(renameAction);
remove.addActionListener(removeAction);
new MoveActionListener(false, -1, m1);
new MoveActionListener(false, 1, p1);
new MoveActionListener(true, -1, ma);
new MoveActionListener(true, 1, pa);
new MoveActionListener(false, -2, m2);
new MoveActionListener(false, 2, p2);
new MoveActionListener(true, -2, mb);
new MoveActionListener(true, 2, pb);
add(editSelected);
add(new JSeparator());
add(rotateLeft);
add(rotateRight);
add(mirrorHorizontal);
add(mirrorVertical);
add(inverted);
add(new JSeparator());
add(rename);
add(m1);
add(p1);
add(ma);
add(pa);
add(m2);
add(p2);
add(mb);
add(pb);
add(remove);
add(new JSeparator());
for (Map.Entry<String, String> en : Context.getPageTags().entrySet()) {
JMenuItem add = new JMenuItem(Messages.getString("PAGE_POPUP_ADD_TAG", en.getValue()));
add.addActionListener(new TagActionListener(en.getKey(), true));
add(add);
}
for (Map.Entry<String, String> en : Context.getPageTags().entrySet()) {
JMenuItem rem = new JMenuItem(Messages.getString("PAGE_POPUP_REMOVE_TAG", en.getValue()));
rem.addActionListener(new TagActionListener(en.getKey(), false));
add(rem);
}
}
boolean isMovePossible(boolean letter, int count) {
List<String> pagesList = book.listPages();
Set<String> pagesSet = new HashSet<>(pagesList);
List<String> movedPages = new ArrayList<>();
for (String p : pagesList) {
if (selectedPages.contains(p)) {
pagesSet.remove(p);
movedPages.add(p);
}
}
for (int i = 0; i < movedPages.size(); i++) {
movedPages.set(i, Book2.incPagePos(movedPages.get(i), letter, count));
}
for (String p : movedPages) {
if (pagesSet.contains(p)) {
return false;
}
}
return true;
}
boolean isAllLetters() {
List<String> pagesList = book.listPages();
for (String p : pagesList) {
if (selectedPages.contains(p)) {
char last = p.charAt(p.length() - 1);
if (last >= '0' && last <= '9') {
return false;
}
}
}
return true;
}
ActionListener removeAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (JOptionPane.showConfirmDialog(DataStorage.mainFrame,
Messages.getString("PAGE_POPUP_CONFIRM_REMOVE", selectedIndexes.size()), "Confirm",
JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) {
return;
}
LOG.info("Remove pages " + selectedIndexes);
try {
List<String> pagesList = book.listPages();
for (String p : pagesList) {
if (selectedPages.contains(p)) {
PageFileInfo pfi = new PageFileInfo(book, p);
book.removePage(p);
File jpg = pfi.getPreviewFile();
File raw = pfi.getOriginalFile();
if (jpg.exists() && !jpg.delete()) {
throw new Exception(Messages.getString("PAGE_POPUP_ERROR_REMOVE", p));
}
if (raw.exists() && !raw.delete()) {
throw new Exception(Messages.getString("PAGE_POPUP_ERROR_REMOVE", p));
}
}
}
book.save();
} catch (Throwable ex) {
LOG.error("Error remove : ", ex);
JOptionPane.showMessageDialog(null, "Error: " + ex.getClass() + " / " + ex.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
}
controller.show();
}
};
ActionListener editSelectedAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
EditPageController.show(controller, selectedPages, selectedPages.get(0));
}
};
String showPageNumberDialog() {
StringBuilder result = new StringBuilder();
PageNumber dialog = new PageNumber(DataStorage.mainFrame, true);
dialog.setTitle(Messages.getString("PAGE_NUMBER_TITLE", selectedPages.size(),
Book2.simplifyPageNumber(selectedPages.get(0))));
dialog.statusLabel.setText(" ");
dialog.renameButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (dialog.cbInversed.isSelected()) {
result.append('-');
}
result.append(dialog.txtNumber.getText().trim());
dialog.dispose();
}
});
dialog.getRootPane().setDefaultButton(dialog.renameButton);
dialog.txtNumber.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) {
check(e.getDocument());
}
@Override
public void insertUpdate(DocumentEvent e) {
check(e.getDocument());
}
@Override
public void changedUpdate(DocumentEvent e) {
check(e.getDocument());
}
void check(Document d) {
dialog.statusLabel.setText(" ");
try {
String newText = d.getText(0, d.getLength()).trim();
newText = Book2.formatPageNumber(newText);
if (StringUtils.isEmpty(newText)) {
dialog.renameButton.setEnabled(false);
dialog.statusLabel.setText(Messages.getString("PAGE_NUMBER_ERROR_WRONG"));
dialog.statusLabel.setForeground(Color.RED);
} else {
String exist = null;
String testNumber = newText;
for (int i = 0; i < selectedPages.size(); i++) {
Book2.PageInfo pi = book.getPageInfo(testNumber);
if (pi != null) {
exist = testNumber;
break;
}
testNumber = Book2.incPage(testNumber, 1);
}
if (exist != null) {
dialog.renameButton.setEnabled(false);
dialog.statusLabel.setText(
Messages.getString("PAGE_NUMBER_ERROR_EXIST", Book2.simplifyPageNumber(exist)));
dialog.statusLabel.setForeground(Color.RED);
} else {
dialog.renameButton.setEnabled(true);
dialog.statusLabel.setText(
Messages.getString("PAGE_NUMBER_RESULT", newText, Book2.incPage(testNumber, -1)));
dialog.statusLabel.setForeground(Color.BLACK);
}
}
} catch (BadLocationException ex) {
dialog.renameButton.setEnabled(false);
}
}
});
dialog.setLocationRelativeTo(DataStorage.mainFrame);
dialog.setVisible(true);
return result.toString();
}
ActionListener rotateLeftAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Rotate left");
for (String p : selectedPages) {
PageInfo pi = book.getPageInfo(p);
pi.rotate = (pi.rotate + 3) % 4;
controller.updatePreview(p);
}
}
};
ActionListener rotateRightAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Rotate right");
for (String p : selectedPages) {
PageInfo pi = book.getPageInfo(p);
pi.rotate = (pi.rotate + 1) % 4;
controller.updatePreview(p);
}
}
};
ActionListener mirrorHorizontalAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Mirror horizontal");
for (String p : selectedPages) {
PageInfo pi = book.getPageInfo(p);
pi.mirrorHorizontal = !pi.mirrorHorizontal;
controller.updatePreview(p);
}
}
};
ActionListener mirrorVerticalAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Mirror vertical");
for (String p : selectedPages) {
PageInfo pi = book.getPageInfo(p);
pi.mirrorVertical = !pi.mirrorVertical;
controller.updatePreview(p);
}
}
};
ActionListener invertedAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Inverted");
for (String p : selectedPages) {
PageInfo pi = book.getPageInfo(p);
pi.inverted = !pi.inverted;
controller.updatePreview(p);
}
}
};
ActionListener renameAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String newPage = showPageNumberDialog();
boolean inversed = false;
if (newPage.startsWith("-")) {
newPage = newPage.substring(1);
inversed = true;
}
newPage = Book2.formatPageNumber(newPage);
if (StringUtils.isEmpty(newPage)) {
return;
}
List<String> selected=new ArrayList<>(selectedPages);
if (inversed) {
Collections.reverse(selected);
}
for (String oldPage: selected) {
LOG.info("Rename page from " + oldPage + " to " + newPage);
try {
PageFileInfo pfi = new PageFileInfo(book, oldPage);
PageInfo pi = book.removePage(oldPage);
if (pi == null) {
throw new Exception(Messages.getString("PAGE_POPUP_ERROR_MOVE", oldPage));
}
pi.pageNumber = newPage;
book.addPage(pi);
PageFileInfo pfo = new PageFileInfo(book, newPage);
File jpg = pfi.getPreviewFile();
File raw = pfi.getOriginalFile();
File newJpg = pfo.getPreviewFile();
File newRaw = pfo.getOriginalFile();
if (!jpg.renameTo(newJpg)) {
throw new Exception(Messages.getString("PAGE_POPUP_ERROR_MOVE", oldPage));
}
if (!raw.renameTo(newRaw)) {
throw new Exception(Messages.getString("PAGE_POPUP_ERROR_MOVE", oldPage));
}
book.save();
} catch (Throwable ex) {
LOG.error("Error rename : ", ex);
JOptionPane.showMessageDialog(null, "Error: " + ex.getClass() + " / " + ex.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
}
newPage = Book2.incPage(newPage, 1);
}
controller.show();
}
};
class TagActionListener implements ActionListener {
private final String tag;
private final boolean add;
public TagActionListener(String tag, boolean add) {
this.tag = tag;
this.add = add;
}
@Override
public void actionPerformed(ActionEvent e) {
for (String p : book.listPages()) {
if (selectedPages.contains(p)) {
PageInfo pi = book.getPageInfo(p);
if (add) {
pi.tags.add(tag);
} else {
pi.tags.remove(tag);
}
}
}
}
}
class MoveActionListener implements ActionListener {
private final boolean letter;
private final int count;
public MoveActionListener(boolean letter, int count, JMenuItem menuItem) {
this.letter = letter;
this.count = count;
boolean enabled = isMovePossible(letter, count);
if (letter && !isAllLetters()) {
enabled = false;
}
menuItem.setEnabled(enabled);
if (enabled) {
menuItem.addActionListener(this);
}
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Move pages");
try {
File tempDir = new File(book.getBookDir(), "move-temp.dir");
if (tempDir.exists()) {
throw new Exception(Messages.getString("PAGE_POPUP_ERROR_MOVE_PREVIOUS"));
}
tempDir.mkdirs();
Map<String, PageInfo> movedPages = new TreeMap<>();
Map<String, PageFileInfo> movedPageFiles = new TreeMap<>();
List<String> pagesList = book.listPages();
for (String p : pagesList) {
if (selectedPages.contains(p)) {
PageFileInfo pfi = new PageFileInfo(book, p);
movedPageFiles.put(p, pfi);
File preview = pfi.getPreviewFile();
File orig = pfi.getOriginalFile();
File tempPreview = new File(tempDir, "preview-" + preview.getName());
File tempOrig = new File(tempDir, orig.getName());
if (!preview.renameTo(tempPreview)) {
throw new Exception(Messages.getString("PAGE_POPUP_ERROR_MOVE", p));
}
if (!orig.renameTo(tempOrig)) {
throw new Exception(Messages.getString("PAGE_POPUP_ERROR_MOVE", p));
}
}
}
for (String p : pagesList) {
if (selectedPages.contains(p)) {
PageInfo pi = book.removePage(p);
movedPages.put(p, pi);
}
}
for (Map.Entry<String, PageInfo> en : movedPages.entrySet()) {
String newPage = Book2.incPagePos(en.getKey(), letter, count);
en.getValue().pageNumber = newPage;
book.addPage(en.getValue());
}
book.save();
for (String p : movedPages.keySet()) {
PageFileInfo pfi = movedPageFiles.get(p);
File tempPreview = new File(tempDir, "preview-" + pfi.getPreviewFile().getName());
File tempOrig = new File(tempDir, pfi.getOriginalFile().getName());
String newPage = Book2.incPagePos(p, letter, count);
PageFileInfo pfo = new PageFileInfo(book, newPage);
File preview = pfo.getPreviewFile();
File orig = pfo.getOriginalFile();
if (!tempPreview.renameTo(preview)) {
throw new Exception(Messages.getString("PAGE_POPUP_ERROR_MOVE", p));
}
if (!tempOrig.renameTo(orig)) {
throw new Exception(Messages.getString("PAGE_POPUP_ERROR_MOVE", p));
}
}
tempDir.delete();
} catch (Throwable ex) {
LOG.error("Error remove : ", ex);
JOptionPane.showMessageDialog(null, "Error: " + ex.getClass() + " / " + ex.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
}
controller.resetAllPreviews();
controller.show();
}
}
}
| 21,565 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
SelectionController.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/ui/book/SelectionController.java | package org.alex73.skarynka.scan.ui.book;
import java.awt.Container;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class SelectionController {
private final Container pageContainer;
private Set<Integer> selected = new TreeSet<>();
private int start = -1, end = -1;
public SelectionController(Container pageContainer) {
this.pageContainer = pageContainer;
}
void reset() {
selected.clear();
start = -1;
end = -1;
}
void clear() {
for (int i : selected) {
repaint(i);
}
reset();
}
void setStart(int index) {
for (int i = Math.min(start, end); i <= Math.max(start, end); i++) {
if (i >= 0) {
selected.remove(i);
repaint(i);
}
}
this.start = index;
}
void setEnd(int index) {
for (int i = Math.min(start, end); i <= Math.max(start, end); i++) {
if (i >= 0) {
selected.remove(i);
repaint(i);
}
}
this.end = index;
for (int i = Math.min(start, end); i <= Math.max(start, end); i++) {
if (i >= 0) {
selected.add(i);
repaint(i);
}
}
}
void change(int index) {
if (!selected.remove(index)) {
selected.add(index);
}
repaint(index);
}
boolean isSelected(int index) {
return selected.contains(index);
}
void addSelectionInterval(int start, int end) {
for (int i = Math.min(start, end); i <= Math.max(start, end); i++) {
selected.add(i);
repaint(i);
}
}
void repaint(int index) {
pageContainer.getComponent(index).repaint();
}
List<Integer> getSelected() {
List<Integer> r = new ArrayList<>(selected);
Collections.sort(r);
return r;
}
}
| 2,035 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
PageComponent.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/ui/book/PageComponent.java | package org.alex73.skarynka.scan.ui.book;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import org.alex73.skarynka.scan.Book2;
import org.alex73.skarynka.scan.Book2.PageInfo;
import org.alex73.skarynka.scan.IPagePreviewChanged;
import org.alex73.skarynka.scan.ui.page.EditPageController;
@SuppressWarnings("serial")
public class PageComponent extends JLabel {
private static final Border borderNone = BorderFactory.createLineBorder(new Color(0, 0, 0, 0));
private static final Border borderFocused = BorderFactory.createLineBorder(Color.RED);
private static final Border borderSelected = BorderFactory.createLineBorder(Color.BLUE);
private final PanelEditController controller;
public PageComponent(String page, PanelEditController controller, boolean selectionEnabled) {
super(Book2.simplifyPageNumber(page));
this.controller = controller;
setName(page);
setBorder(borderNone);
setHorizontalTextPosition(SwingConstants.CENTER);
setVerticalTextPosition(SwingConstants.BOTTOM);
updateImage();
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {
switch (e.getClickCount()) {
case 1:
int index=getIndex();
if (e.isControlDown()) {
controller.selection.change(index);
} else if (e.isShiftDown()) {
controller.selection.setEnd(index);
System.out.println("shift " + controller.selection);
} else {
controller.selection.clear();
controller.selection.setStart(index);
controller.selection.setEnd(index);
}
requestFocus();
break;
case 2:
EditPageController.show(controller, controller.getBook().listPages(), getName());
break;
}
}
if (SwingUtilities.isRightMouseButton(e) && e.getClickCount() == 1) {
if (selectionEnabled && !controller.selection.getSelected().isEmpty()) {
new PagePopupMenu(controller).show(PageComponent.this, e.getX(), e.getY());
}
}
e.consume();
}
});
if (selectionEnabled) {
setFocusable(true);
addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent e) {
repaint();
}
@Override
public void focusGained(FocusEvent e) {
PageInfo pi = controller.getBook().getPageInfo(getName());
Dimension fullImageSize = new Dimension(pi.imageSizeX, pi.imageSizeY);
controller.previewPage.setRotation(pi.rotate);
controller.previewPage.setMirrorHorizontal(pi.mirrorHorizontal);
controller.previewPage.setMirrorVertical(pi.mirrorVertical);
controller.previewPage.setInverted(pi.inverted);
controller.previewPage.getCrops().clear();
controller.previewPage.getCrops()
.add(controller.previewPage.screen2image(new Rectangle(pi.cropPosX, pi.cropPosY,
controller.getBook().cropSizeX, controller.getBook().cropSizeY), fullImageSize));
controller.panel.previewTags.setText(pi.tags.toString());
try {
controller.previewPage.displayImage(controller.getBook().getImage(getName()), 1, 1);
} catch (Exception ex) {
}
}
});
}
}
protected void updateImage() {
controller.previewer.setPreview(getName(), new IPagePreviewChanged() {
@Override
public void show(Image image) {
setIcon(new ImageIcon(image));
}
});
}
private int getIndex() {
for (int i = 0; i < getParent().getComponentCount(); i++) {
if (getParent().getComponent(i) == this) {
return i;
}
}
return -1;
}
@Override
protected void paintBorder(Graphics g) {
int index=getIndex();
if (isFocusOwner()) {
setBorder(borderFocused);
} else if (controller.selection.isSelected(index)) {
setBorder(borderSelected);
} else {
setBorder(borderNone);
}
super.paintBorder(g);
}
}
| 5,323 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
BooksPanel.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/ui/book/BooksPanel.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan.ui.book;
import org.alex73.skarynka.scan.Messages;
/**
*
* @author Aleś Bułojčyk <alex73mail@gmail.com>
*/
public class BooksPanel extends javax.swing.JPanel {
/**
* Creates new form BooksPanel
*/
public BooksPanel() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
menuProcess = new javax.swing.JPopupMenu();
itemFinish = new javax.swing.JMenuItem();
jLabel1 = new javax.swing.JLabel();
txtNewName = new javax.swing.JTextField();
btnCreate = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
table = new javax.swing.JTable();
itemFinish.setText(Messages.getString("BOOK_MENU_STATUS_FINISH")); // NOI18N
menuProcess.add(itemFinish);
setLayout(new java.awt.GridBagLayout());
jLabel1.setText(Messages.getString("PANEL_BOOK_NEW")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
add(jLabel1, gridBagConstraints);
txtNewName.setColumns(30);
txtNewName.setMinimumSize(new java.awt.Dimension(200, 19));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
add(txtNewName, gridBagConstraints);
btnCreate.setText(Messages.getString("PANEL_BOOK_CREATE")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
add(btnCreate, gridBagConstraints);
jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
table.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(table);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
add(jScrollPane1, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
public javax.swing.JButton btnCreate;
public javax.swing.JMenuItem itemFinish;
public javax.swing.JLabel jLabel1;
public javax.swing.JScrollPane jScrollPane1;
public javax.swing.JPopupMenu menuProcess;
public javax.swing.JTable table;
public javax.swing.JTextField txtNewName;
// End of variables declaration//GEN-END:variables
}
| 4,734 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
BookRow.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/ui/book/BookRow.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan.ui.book;
import org.alex73.skarynka.scan.Book2;
/**
* Bean for store book information for display in the books list.
*
* @author Aleś Bułojčyk <alex73mail@gmail.com>
*/
public class BookRow {
public final String bookName;
public final int pagesCount;
public final String status;
public final String info;
public final boolean local;
public BookRow(Book2 book) {
bookName = book.getName();
pagesCount = book.getPagesCount();
status = book.getStatusText();
local = book.local;
StringBuilder s = new StringBuilder();
int dpi = book.dpi != 0 ? book.dpi : 100;
int w = Math.round(2.54f * book.cropSizeX / dpi);
int h = Math.round(2.54f * book.cropSizeY / dpi);
s.append(w).append('x').append(h).append("cm : ");
s.append(book.cropSizeX).append('x').append(book.cropSizeY).append(" ");
s.append(dpi).append("dpi ");
if (book.scale != 100) {
s.append(book.scale).append("%");
}
s.append(" zoom=").append(book.zoom);
s.append("-> " + (book.cropSizeX * book.scale / 100) + "x" + (book.cropSizeY * book.scale / 100));
info = s.toString();
}
}
| 2,155 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
PanelEdit.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/ui/book/PanelEdit.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan.ui.book;
/**
*
* @author Aleś Bułojčyk <alex73mail@gmail.com>
*/
public class PanelEdit extends javax.swing.JPanel {
/**
* Creates new form PanelEdit
*/
public PanelEdit() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
jSplitPane1 = new javax.swing.JSplitPane();
pagesScrollBar = new javax.swing.JScrollPane();
pagesPanel = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
previewOrig = new javax.swing.JToggleButton();
previewFull = new javax.swing.JToggleButton();
previewInc = new javax.swing.JButton();
previewDec = new javax.swing.JButton();
previewTags = new javax.swing.JLabel();
scrollPreview = new javax.swing.JScrollPane();
setLayout(new java.awt.BorderLayout());
jSplitPane1.setResizeWeight(0.5);
pagesScrollBar.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
pagesPanel.setLayout(new java.awt.GridLayout(0, 5, 10, 10));
pagesScrollBar.setViewportView(pagesPanel);
jSplitPane1.setLeftComponent(pagesScrollBar);
jPanel1.setLayout(new java.awt.BorderLayout());
buttonGroup1.add(previewOrig);
previewOrig.setText("1:1");
jPanel2.add(previewOrig);
buttonGroup1.add(previewFull);
previewFull.setText("#");
jPanel2.add(previewFull);
previewInc.setText("+");
jPanel2.add(previewInc);
previewDec.setText("-");
jPanel2.add(previewDec);
previewTags.setText("[]");
jPanel2.add(previewTags);
jPanel1.add(jPanel2, java.awt.BorderLayout.NORTH);
jPanel1.add(scrollPreview, java.awt.BorderLayout.CENTER);
jSplitPane1.setRightComponent(jPanel1);
add(jSplitPane1, java.awt.BorderLayout.CENTER);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
public javax.swing.ButtonGroup buttonGroup1;
public javax.swing.JPanel jPanel1;
public javax.swing.JPanel jPanel2;
public javax.swing.JSplitPane jSplitPane1;
public javax.swing.JPanel pagesPanel;
public javax.swing.JScrollPane pagesScrollBar;
public javax.swing.JButton previewDec;
public javax.swing.JToggleButton previewFull;
public javax.swing.JButton previewInc;
public javax.swing.JToggleButton previewOrig;
public javax.swing.JLabel previewTags;
public javax.swing.JScrollPane scrollPreview;
// End of variables declaration//GEN-END:variables
}
| 3,973 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
PanelEditController.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/ui/book/PanelEditController.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan.ui.book;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import org.alex73.skarynka.scan.Book2;
import org.alex73.skarynka.scan.DataStorage;
import org.alex73.skarynka.scan.ITabController;
import org.alex73.skarynka.scan.Messages;
import org.alex73.skarynka.scan.PagePreviewer;
import org.alex73.skarynka.scan.common.ImageViewPane;
import org.alex73.skarynka.scan.process.ProcessDaemon;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Controller for edit book panel.
*
* @author Aleś Bułojčyk <alex73mail@gmail.com>
*/
public class PanelEditController implements ITabController {
private static Logger LOG = LoggerFactory.getLogger(PanelEditController.class);
private final Book2 book;
protected final PanelEdit panel;
protected final ImageViewPane previewPage;
protected SelectionController selection;
protected PagePreviewer previewer;
private List<JMenuItem> menuItems = new ArrayList<>();
@Override
public String getTabName() {
return book.getName();
}
@Override
public Component getTabComponent() {
return panel;
}
public PanelEditController(Book2 book) throws Exception {
this.book = book;
panel = new PanelEdit();
panel.setName(book.getName());
selection = new SelectionController(panel.pagesPanel);
panel.pagesScrollBar.getVerticalScrollBar().setUnitIncrement(20);
panel.pagesScrollBar.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
resize();
}
});
previewPage = new ImageViewPane();
panel.scrollPreview.setViewportView(previewPage);
panel.previewOrig.addActionListener((e) -> {
BufferedImage image = previewPage.getImage();
previewPage.setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));
panel.scrollPreview.revalidate();
});
panel.previewFull.addActionListener((e) -> {
previewPage.setPreferredSize(new Dimension(50, 50));
panel.scrollPreview.revalidate();
});
previewer = new PagePreviewer(book);
List<String> pages = book.listPages();
for (String p : pages) {
ProcessDaemon.createPreviewIfNeed(book, p);
}
show();
}
KeyListener KEY_LISTENER = new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
Point p = getFocusPosition();
if (p == null) {
return;
}
boolean moved = false;
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
p.y--;
moved = true;
break;
case KeyEvent.VK_DOWN:
p.y++;
moved = true;
break;
case KeyEvent.VK_LEFT:
p.x--;
moved = true;
break;
case KeyEvent.VK_RIGHT:
p.x++;
moved = true;
break;
case KeyEvent.VK_A:
if (e.isControlDown()) {
selection.addSelectionInterval(0, panel.pagesPanel.getComponentCount() - 1);
e.consume();
}
break;
case KeyEvent.VK_END:
if (e.isShiftDown()) {
p = getPointByIndex(panel.pagesPanel.getComponentCount() - 1);
moved=true;
e.consume();
}
break;
case KeyEvent.VK_HOME:
if (e.isShiftDown()) {
p = getPointByIndex(0);
moved=true;
e.consume();
}
break;
}
if (moved) {
PageComponent c = setFocusPosition(p);
if (c != null) {
if (!e.isShiftDown()) {
selection.clear();
selection.setStart(getPointIndex(p));
}
selection.setEnd(getPointIndex(p));
if (c != null) {
((JComponent)c.getParent()).scrollRectToVisible(c.getBounds());
}
}
e.consume();
}
}
};
Point getFocusPosition() {
int idx = -1;
for (int i = 0; i < panel.pagesPanel.getComponentCount(); i++) {
if (panel.pagesPanel.getComponent(i).isFocusOwner()) {
idx = i;
break;
}
}
if (idx < 0) {
return null;
}
return getPointByIndex(idx);
}
int getPointIndex(Point p) {
GridLayout grid = (GridLayout) panel.pagesPanel.getLayout();
return p.x + grid.getColumns() * p.y;
}
Point getPointByIndex(int idx) {
GridLayout grid = (GridLayout) panel.pagesPanel.getLayout();
Point r = new Point();
r.x = idx % grid.getColumns();
r.y = idx / grid.getColumns();
return r;
}
PageComponent setFocusPosition(Point p) {
int idx = getPointIndex(p);
if (idx >= 0 && idx < panel.pagesPanel.getComponentCount()) {
PageComponent c = (PageComponent) panel.pagesPanel.getComponent(idx);
c.requestFocus();
return c;
} else {
return null;
}
}
@SuppressWarnings("serial")
void bind(int vk, ActionListener listener) {
panel.pagesPanel.getInputMap().put(KeyStroke.getKeyStroke(vk, 0), "ACTION_KEY_" + vk);
panel.pagesPanel.getActionMap().put("ACTION_KEY_" + vk, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
listener.actionPerformed(e);
}
});
}
public Book2 getBook() {
return book;
}
public PanelEdit getPanel() {
return panel;
}
@Override
public void close() {
previewer.finish();
try {
book.save();
} catch (Exception ex) {
LOG.error("Error save book '" + book.getName() + "'", ex);
JOptionPane.showMessageDialog(DataStorage.mainFrame,
Messages.getString("ERROR_BOOK_SAVE", book.getName(), ex.getMessage()),
Messages.getString("ERROR_TITLE"), JOptionPane.ERROR_MESSAGE);
return;
}
}
@Override
public void deactivate() {
for (JMenuItem item : menuItems) {
DataStorage.mainFrame.workMenu.remove(item);
}
menuItems.clear();
DataStorage.mainFrame.workMenu.setEnabled(false);
DataStorage.mainFrame.viewMenu.setEnabled(false);
}
@Override
public void activate() {
DataStorage.mainFrame.workMenu.setEnabled(true);
DataStorage.mainFrame.viewMenu.setEnabled(true);
Set<String> cameras = new TreeSet<>();
for (String page : book.listPages()) {
Book2.PageInfo pi = book.getPageInfo(page);
if (pi.camera != null) {
cameras.add(pi.camera);
}
}
for (String camera : cameras) {
JMenuItem item = new JMenuItem(Messages.getString("MENU_BOOK_ROTATE", camera));
item.setName("MENU_BOOK_ROTATE");
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for (String page : book.listPages()) {
Book2.PageInfo pi = book.getPageInfo(page);
if (camera.equals(pi.camera)) {
pi.rotate = (pi.rotate + 1) % 4;
}
}
try {
book.save();
} catch (Exception ex) {
LOG.error("Error save book '" + book.getName() + "'", ex);
JOptionPane.showMessageDialog(DataStorage.mainFrame,
Messages.getString("ERROR_BOOK_SAVE", book.getName(), ex.getMessage()),
Messages.getString("ERROR_TITLE"), JOptionPane.ERROR_MESSAGE);
}
resetAllPreviews();
show();
}
});
menuItems.add(item);
DataStorage.mainFrame.workMenu.add(item);
}
}
public void resetAllPreviews() {
previewer.reset();
}
public void updatePreview(String page) {
previewer.updatePreview(page);
}
public synchronized PanelEdit show() {
panel.pagesPanel.removeAll();
selection.reset();
List<String> pages = book.listPages();
switch (DataStorage.view) {
case SEQ:
// show only sequences
String prev = "", prevLabelStart = null;
JLabel prevLabel = null;
for (String page : pages) {
String prevInc = Book2.incPage(prev, 1);
if (page.equals(prevInc)) {
// sequence
prev = prevInc;
continue;
}
if (prevLabel != null && !prev.equals(prevLabelStart)) {
prevLabel.setText(prevLabel.getText() + ".." + Book2.simplifyPageNumber(prev));
}
prevLabel = createPage(page, false);
prev = prevLabelStart = page;
}
if (prevLabel != null && !prev.equals(prevLabelStart)) {
prevLabel.setText(prevLabel.getText() + ".." + Book2.simplifyPageNumber(prev));
}
break;
case ALL:
// show all pages
for (String page : pages) {
createPage(page, true);
}
break;
case CROP_ERRORS:
for (String page : pages) {
Book2.PageInfo pi = book.getPageInfo(page);
if (pi.cropPosX < 0 || pi.cropPosY < 0) {
createPage(page, false);
}
}
break;
case ODD:
for (String page : pages) {
char e = page.charAt(page.length() - 1);
if (e % 2 == 1) {
createPage(page, true);
}
}
break;
case EVEN:
for (String page : pages) {
char e = page.charAt(page.length() - 1);
if (e % 2 == 0) {
createPage(page, true);
}
}
break;
case TAG:
for (String page : pages) {
Book2.PageInfo pi = book.getPageInfo(page);
if (pi.tags.contains(DataStorage.viewTag)) {
createPage(page, false);
}
}
break;
}
for (int i = 0; i < panel.pagesPanel.getComponentCount(); i++) {
panel.pagesPanel.getComponent(i).addKeyListener(KEY_LISTENER);
}
resize();
panel.pagesPanel.revalidate();
panel.pagesPanel.repaint();
return panel;
}
PageComponent createPage(String page, boolean selectionEnabled) {
PageComponent p = new PageComponent(page, this, selectionEnabled);
panel.pagesPanel.add(p);
return p;
}
void resize() {
int width = panel.pagesScrollBar.getViewport().getWidth();
GridLayout layout = (GridLayout) panel.pagesPanel.getLayout();
int perRow = width / (DataStorage.previewMaxWidth + layout.getHgap());
if (perRow == 0) {
perRow = 1;
}
layout.setColumns(perRow);
panel.pagesPanel.revalidate();
}
String getPageByIndex(int index) {
return ((PageComponent) panel.pagesPanel.getComponent(index)).getName();
}
}
| 13,638 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
ScanDialog.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/ui/scan/ScanDialog.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan.ui.scan;
import org.alex73.skarynka.scan.Messages;
/**
* @author Aleś Bułojčyk <alex73mail@gmail.com>
*/
public class ScanDialog extends javax.swing.JDialog {
/**
* Creates new form ScanDialog
*/
public ScanDialog(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
controlLeft = new org.alex73.skarynka.scan.ui.scan.ScanControlPanel();
liveLeft = new org.alex73.skarynka.scan.common.ImageViewPane();
liveRight = new org.alex73.skarynka.scan.common.ImageViewPane();
controlRight = new org.alex73.skarynka.scan.ui.scan.ScanControlPanel();
jPanel1 = new javax.swing.JPanel();
lblStatus = new javax.swing.JLabel();
btnScan = new javax.swing.JButton();
btnRescan = new javax.swing.JButton();
btnClose = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle(Messages.getString("SCAN_CONTROL_TITLE")); // NOI18N
getContentPane().setLayout(new java.awt.GridBagLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
getContentPane().add(controlLeft, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
getContentPane().add(liveLeft, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
getContentPane().add(liveRight, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
getContentPane().add(controlRight, gridBagConstraints);
jPanel1.setLayout(new java.awt.GridBagLayout());
lblStatus.setForeground(java.awt.Color.red);
lblStatus.setText(" ");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
jPanel1.add(lblStatus, gridBagConstraints);
btnScan.setText(Messages.getString("SCAN_CONTROL_BUTTON_SCAN")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 30);
jPanel1.add(btnScan, gridBagConstraints);
btnRescan.setText(Messages.getString("SCAN_CONTROL_BUTTON_RESCAN")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
jPanel1.add(btnRescan, gridBagConstraints);
btnClose.setText(Messages.getString("SCAN_CONTROL_BUTTON_STOP")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(3, 30, 3, 3);
jPanel1.add(btnClose, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
getContentPane().add(jPanel1, gridBagConstraints);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ScanDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ScanDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ScanDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ScanDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
ScanDialog dialog = new ScanDialog(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
public javax.swing.JButton btnClose;
public javax.swing.JButton btnRescan;
public javax.swing.JButton btnScan;
public org.alex73.skarynka.scan.ui.scan.ScanControlPanel controlLeft;
public org.alex73.skarynka.scan.ui.scan.ScanControlPanel controlRight;
public javax.swing.JPanel jPanel1;
public javax.swing.JLabel lblStatus;
public org.alex73.skarynka.scan.common.ImageViewPane liveLeft;
public org.alex73.skarynka.scan.common.ImageViewPane liveRight;
// End of variables declaration//GEN-END:variables
}
| 8,265 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
ScanDialogController.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/ui/scan/ScanDialogController.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan.ui.scan;
import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import org.alex73.skarynka.scan.Book2;
import org.alex73.skarynka.scan.Context;
import org.alex73.skarynka.scan.DataStorage;
import org.alex73.skarynka.scan.Messages;
import org.alex73.skarynka.scan.common.ImageViewPane;
import org.alex73.skarynka.scan.hid.HIDScanController;
import org.alex73.skarynka.scan.ui.book.PanelEditController;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Controller for scan dialog.
*
* @author Aleś Bułojčyk <alex73mail@gmail.com>
*/
public class ScanDialogController {
private static Logger LOG = LoggerFactory.getLogger(ScanDialogController.class);
private final PanelEditController panelController;
private final Book2 book;
private ScanDialog dialog;
private String prev1, prev2;
private Dimension imageSize;
public static void show(PanelEditController panelController) {
new ScanDialogController(panelController);
}
private ScanDialogController(PanelEditController panelController) {
this.panelController = panelController;
this.book = panelController.getBook();
int currentZoom = DataStorage.device.getZoom();
Dimension[] deviceImageSizes = DataStorage.device.getImageSize();
imageSize = deviceImageSizes[0];
for (int i = 1; i < deviceImageSizes.length; i++) {
if (!imageSize.equals(deviceImageSizes[i])) {
JOptionPane.showMessageDialog(DataStorage.mainFrame,
Messages.getString("ERROR_WRONG_NOTEQUALSSIZE"), Messages.getString("ERROR_TITLE"),
JOptionPane.ERROR_MESSAGE);
return;
}
}
int pagesCount = book.getPagesCount();
if (pagesCount > 0) {
int bookZoom = book.zoom;
if (bookZoom != currentZoom) {
if (JOptionPane.showConfirmDialog(DataStorage.mainFrame,
Messages.getString("ERROR_WRONG_ZOOM", pagesCount, bookZoom, currentZoom),
Messages.getString("ERROR_TITLE"), JOptionPane.OK_CANCEL_OPTION,
JOptionPane.WARNING_MESSAGE) != JOptionPane.OK_OPTION) {
return;
}
}
}
book.zoom = currentZoom;
String dpi = Context.getSettings().get("dpi." + book.zoom);
if (dpi != null) {
book.dpi = Integer.parseInt(dpi);
} else {
book.dpi = 300;
}
dialog = new ScanDialog(DataStorage.mainFrame, true);
dialog.btnClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
});
dialog.addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
DataStorage.device.setPreviewPanels();
panelController.show();
}
});
init(dialog.controlLeft, dialog.liveLeft);
init(dialog.controlRight, dialog.liveRight);
checkNumbers();
showStatus();
boolean[] visible = DataStorage.device.setPreviewPanels(dialog.liveLeft, dialog.liveRight);
dialog.controlLeft.setVisible(visible[0]);
dialog.controlRight.setVisible(visible[1]);
dialog.liveLeft.setVisible(visible[0]);
dialog.liveRight.setVisible(visible[1]);
int[] rotations = DataStorage.device.getRotations();
dialog.liveLeft.setRotation(rotations[0]);
dialog.liveRight.setRotation(rotations[1]);
dialog.setBounds(GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds());
dialog.validate();
dialog.controlLeft.txtNumber.setVisible(false);
dialog.controlLeft.txtNumber.setVisible(false);
int keyCode = HIDScanController.getKeyCode(Context.getSettings().get("hidscan-keys"));
if (keyCode != 0) {
addAction(keyCode, actionScan);
}
if (keyCode != KeyEvent.VK_F1) {
addAction(KeyEvent.VK_F1, actionScan);
}
dialog.btnScan.addActionListener(actionScan);
addAction(KeyEvent.VK_F2, actionRescan);
dialog.btnRescan.addActionListener(actionRescan);
dialog.setVisible(true);
}
@SuppressWarnings("serial")
Action actionScan = new AbstractAction("scan") {
@Override
public void actionPerformed(ActionEvent e) {
if (dialog.btnScan.isEnabled()) {
scan(dialog.liveLeft.getPageNumber(), dialog.liveRight.getPageNumber());
showStatus();
checkNumbers();
}
}
};
@SuppressWarnings("serial")
Action actionRescan = new AbstractAction("rescan") {
@Override
public void actionPerformed(ActionEvent e) {
if (prev1 == null && prev2 == null) {
return;
}
if (dialog.btnRescan.isEnabled()) {
scan(prev1, prev2);
showStatus();
checkNumbers();
}
}
};
String s(Dimension s) {
return s.width + "x" + s.height;
}
void scan(String p1, String p2) {
String bookPath = book.getBookDir().getAbsolutePath() + "/";
String p1f = Book2.formatPageNumber(p1);
String p2f = Book2.formatPageNumber(p2);
prev1 = p1f;
prev2 = p2f;
dialog.btnRescan.setEnabled(true);
String p1p = dialog.liveLeft.getStrikeOut() || !dialog.controlLeft.isVisible() ? null
: bookPath + p1f;
String p2p = dialog.liveRight.getStrikeOut() || !dialog.controlRight.isVisible() ? null
: bookPath + p2f;
try {
String[] camerasIds = DataStorage.device.scan(p1p, p2p);
if (p1p != null) {
Book2.PageInfo pi = book.new PageInfo(p1f);
pi.rotate = dialog.liveLeft.getRotation();
pi.tags.clear();
pi.tags.addAll(dialog.controlLeft.tags.getValues());
pi.camera = camerasIds[0];
pi.imageSizeX = imageSize.width;
pi.imageSizeY = imageSize.height;
pi.pageOriginalFileExt = DataStorage.device.getScannedFileExt();
book.addPage(pi);
panelController.updatePreview(p1f);
}
if (p2p != null) {
Book2.PageInfo pi = book.new PageInfo(p2f);
pi.rotate = dialog.liveRight.getRotation();
pi.tags.clear();
pi.tags.addAll(dialog.controlRight.tags.getValues());
pi.camera = camerasIds[1];
pi.imageSizeX = imageSize.width;
pi.imageSizeY = imageSize.height;
pi.pageOriginalFileExt = DataStorage.device.getScannedFileExt();
book.addPage(pi);
panelController.updatePreview(p2f);
}
} catch (Exception ex) {
LOG.debug("Error scan", ex);
JOptionPane.showMessageDialog(DataStorage.mainFrame,
Messages.getString("ERROR_SCAN", ex.getClass().getName(), ex.getMessage(),
Messages.getString("ERROR_TITLE"), JOptionPane.ERROR_MESSAGE));
}
try {
book.save();
} catch (Exception ex) {
LOG.debug("Error book save", ex);
JOptionPane.showMessageDialog(DataStorage.mainFrame,
Messages.getString("ERROR_BOOK_SAVE", book.getName(), ex.getMessage()),
Messages.getString("ERROR_TITLE"), JOptionPane.ERROR_MESSAGE);
}
dialog.liveLeft.setPageNumber(Book2.simplifyPageNumber(Book2.incPage(p1f, "".equals(p2f) ? 1 : 2)));
dialog.liveRight.setPageNumber(Book2.simplifyPageNumber(Book2.incPage(p2f, 2)));
}
void showStatus() {
try {
String[] status = DataStorage.device.getStatus();
if (status.length >= 1 && dialog.controlLeft.isVisible()) {
dialog.controlLeft.labelInfo.setText(status[0]);
}
if (status.length >= 2 && dialog.controlRight.isVisible()) {
dialog.controlRight.labelInfo.setText(status[1]);
}
} catch (Exception ex) {
LOG.debug("Error show status", ex);
JOptionPane.showMessageDialog(DataStorage.mainFrame,
Messages.getString("ERROR_SCAN", ex.getClass().getName(), ex.getMessage(),
Messages.getString("ERROR_TITLE"), JOptionPane.ERROR_MESSAGE));
}
}
void init(ScanControlPanel control, ImageViewPane live) {
control.btnSkip.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
live.setStrikeout(control.btnSkip.isSelected());
checkNumbers();
}
});
control.btnNumber.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
control.txtNumber.setVisible(true);
control.txtNumber.setText(live.getPageNumber());
control.txtNumber.requestFocus();
}
});
control.txtNumber.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == '\n') { // ENTER
live.setPageNumber(Book2.simplifyPageNumber(control.txtNumber.getText()));
control.txtNumber.setVisible(false);
control.btnNumber.requestFocus();
checkNumbers();
} else if (e.getKeyChar() == KeyEvent.VK_ESCAPE) { // ESC
control.txtNumber.setVisible(false);
control.btnNumber.requestFocus();
}
}
});
control.tags.setup(Context.getPageTags());
}
void checkNumbers() {
dialog.btnScan.setEnabled(false);
dialog.btnRescan.setEnabled(false);
dialog.lblStatus.setText(" ");
prev1 = null;
prev2 = null;
boolean allowRescan = false;
String p1 = dialog.liveLeft.getPageNumber();
String p1f = Book2.formatPageNumber(p1);
String p2 = dialog.liveRight.getPageNumber();
String p2f = Book2.formatPageNumber(p2);
if (dialog.controlLeft.isVisible() && !dialog.liveLeft.getStrikeOut()) {
if (StringUtils.isEmpty(p1)) {
dialog.lblStatus.setText(Messages.getString("SCAN_CONTROL_ERROR_NONE_PAGE"));
return;
}
if (StringUtils.isEmpty(p1f)) {
dialog.lblStatus.setText(Messages.getString("SCAN_CONTROL_ERROR_WRONG_PAGE"));
return;
}
if (book.pageExist(p1)) {
dialog.lblStatus.setText(Messages.getString("SCAN_CONTROL_ERROR_EXIST_PAGES", p1));
}
}
if (dialog.controlRight.isVisible() && !dialog.liveRight.getStrikeOut()) {
if (StringUtils.isEmpty(p2)) {
dialog.lblStatus.setText(Messages.getString("SCAN_CONTROL_ERROR_NONE_PAGE"));
return;
}
if (StringUtils.isEmpty(p2f)) {
dialog.lblStatus.setText(Messages.getString("SCAN_CONTROL_ERROR_WRONG_PAGE"));
return;
}
if (book.pageExist(p2)) {
dialog.lblStatus.setText(Messages.getString("SCAN_CONTROL_ERROR_EXIST_PAGES", p2));
}
}
if (!dialog.liveLeft.getStrikeOut() && !dialog.liveRight.getStrikeOut()) {
if (StringUtils.equals(p1f, p2f)) {
dialog.lblStatus.setText(Messages.getString("SCAN_CONTROL_ERROR_SAME_PAGES"));
return;
}
}
if (!dialog.liveLeft.getStrikeOut() || !dialog.liveRight.getStrikeOut()) {
dialog.btnScan.setEnabled(true);
}
}
void addAction(int keyCode, Action action) {
InputMap im = dialog.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
im.put(KeyStroke.getKeyStroke(keyCode, 0), action.getValue(Action.NAME));
dialog.getRootPane().getActionMap().put(action.getValue(Action.NAME), action);
}
}
| 13,810 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
ScanControlPanel.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/ui/scan/ScanControlPanel.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan.ui.scan;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import org.alex73.skarynka.scan.Messages;
import org.alex73.skarynka.scan.ui.TagsPanel;
/**
* @author Aleś Bułojčyk <alex73mail@gmail.com>
*/
public class ScanControlPanel extends javax.swing.JPanel {
/**
* Creates new form ScanControlPanel
*/
public ScanControlPanel() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
GridBagConstraints gridBagConstraints;
btnSkip = new JToggleButton();
btnNumber = new JButton();
jPanel1 = new JPanel();
txtNumber = new JTextField();
labelInfo = new JLabel();
tags = new TagsPanel();
setLayout(new GridBagLayout());
btnSkip.setText(Messages.getString("SCAN_CONTROL_DISABLE")); // NOI18N
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.insets = new Insets(3, 3, 0, 3);
add(btnSkip, gridBagConstraints);
btnNumber.setText(Messages.getString("SCAN_CONTROL_CHANGE_NUMBER")); // NOI18N
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new Insets(3, 3, 0, 3);
add(btnNumber, gridBagConstraints);
jPanel1.setLayout(new BorderLayout());
txtNumber.setColumns(6);
jPanel1.add(txtNumber, BorderLayout.CENTER);
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.insets = new Insets(3, 3, 0, 3);
add(jPanel1, gridBagConstraints);
labelInfo.setText(Messages.getString("CAMERA_INFO")); // NOI18N
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 20;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.anchor = GridBagConstraints.WEST;
gridBagConstraints.insets = new Insets(3, 3, 0, 3);
add(labelInfo, gridBagConstraints);
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new Insets(3, 3, 3, 3);
add(tags, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
public JButton btnNumber;
public JToggleButton btnSkip;
public JPanel jPanel1;
public JLabel labelInfo;
public TagsPanel tags;
public JTextField txtNumber;
// End of variables declaration//GEN-END:variables
}
| 4,467 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
CameraWorker.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/devices/CameraWorker.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan.devices;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.alex73.chdkptpj.camera.Camera;
import org.alex73.chdkptpj.lua.ChdkPtpJ;
import org.alex73.skarynka.scan.common.ImageViewPane;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Controller for external scan devices. It allows parallel scan from multiple devices, send common commands,
* etc.
*
* Parallel execution required for scan with more than one cameras faster. For example, if one camera requires
* 2 seconds for scanning and transfer data, then two cameras will require 4 seconds if they will not work in
* parallel. It's too much for massive scanning. Instead, all commands will be transferred to cameras in
* parallel. There is one possible issue: most time required for transfer data from camera to computer. If
* cameras connected to the one USB hub, they will transfer data like successive. But even in this case you
* will see a little speed improvement.
*
* @author Aleś Bułojčyk <alex73mail@gmail.com>
*/
public class CameraWorker {
private static Logger LOG = LoggerFactory.getLogger(CameraWorker.class);
private static final int CHDK_ASPECT_WIDTH = 1;
private static final int CHDK_ASPECT_HEIGHT = 2;
private final List<CameraThread> threads = new ArrayList<>();
public CameraWorker(Camera... cameras) throws Exception {
int i = 1;
for (Camera c : cameras) {
if (c != null) {
CameraThread th = new CameraThread(i - 1, c, "Camera " + i);
i++;
th.start();
threads.add(th);
}
}
}
public CameraWorker(List<Camera> cameras) throws Exception {
int i = 1;
for (Camera c : cameras) {
if (c != null) {
CameraThread th = new CameraThread(i - 1, c, "Camera " + i);
i++;
th.start();
threads.add(th);
}
}
}
public boolean[] setPreviewPanels(ImageViewPane... panels) {
boolean[] r = new boolean[panels.length];
for (int i = 0; i < Math.min(threads.size(), panels.length); i++) {
threads.get(i).previewPanel = panels[i];
r[i] = true;
}
for (int i = panels.length; i < threads.size(); i++) {
threads.get(i).previewPanel = null;
}
return r;
}
public void swap() {
if (threads.size() == 2) {
ImageViewPane p0 = threads.get(0).previewPanel;
ImageViewPane p1 = threads.get(1).previewPanel;
Collections.reverse(threads);
setPreviewPanels(p0, p1);
threads.get(0).workerIndex = 0;
threads.get(1).workerIndex = 1;
}
}
public int getCamerasCount() {
return threads.size();
}
public String[] getCamerasIds(Properties props) {
String[] result = new String[threads.size()];
for (int i = 0; i < result.length; i++) {
result[i] = threads.get(i).getSerial();
}
return result;
}
public void exec(CameraCommand command) throws Exception {
final AtomicInteger countForWait = new AtomicInteger(threads.size());
AtomicReference<Exception> error = new AtomicReference<Exception>();
// send command to all cameras
for (int i = 0; i < threads.size(); i++) {
threads.get(i).exec(new CameraCommand() {
@Override
void exec(int workerIndex, Camera camera, ChdkPtpJ lua) throws Exception {
try {
command.exec(workerIndex, camera, lua);
} catch (Exception ex) {
LOG.warn("Error execute camera command", ex);
error.set(ex);
} catch (Throwable ex) {
LOG.warn("Error execute camera command", ex);
error.set(new Exception(ex));
}
int c = countForWait.decrementAndGet();
if (c == 0) {
synchronized (command) {
command.notifyAll();
}
}
}
@Override
public void exec(Camera camera) {
try {
command.exec(camera);
} catch (Exception ex) {
LOG.warn("Error execute camera command", ex);
error.set(ex);
} catch (Throwable ex) {
LOG.warn("Error execute camera command", ex);
error.set(new Exception(ex));
}
int c = countForWait.decrementAndGet();
if (c == 0) {
synchronized (command) {
command.notifyAll();
}
}
}
});
}
// wait for finish all commands
try {
synchronized (command) {
while (countForWait.get() > 0) {
command.wait(10000);
}
}
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
// check for exception
if (error.get() != null) {
throw error.get();
}
}
public static class CameraCommand {
void exec(int workerIndex, Camera camera, ChdkPtpJ lua) throws Exception {
exec(camera);
}
void exec(Camera camera) throws Exception {
}
}
public static class CameraThread extends Thread {
private final Camera camera;
private final String serial;
private final String threadName;
private int workerIndex;
protected ImageViewPane previewPanel;
private LinkedList<CameraCommand> queue = new LinkedList<>();
private ChdkPtpJ lua;
public CameraThread(int workerIndex, Camera camera, String threadName) throws Exception {
this.camera = camera;
this.serial = camera.getDevice().getSerialNumberString().trim();
this.threadName = threadName;
this.workerIndex = workerIndex;
camera.connect();
lua = new ChdkPtpJ(camera, "lua-orig");
}
@Override
public void run() {
Thread.currentThread().setName(threadName);
try {
while (true) {
CameraCommand cmd;
synchronized (queue) {
cmd = queue.poll();
}
if (cmd != null) {
// command ready for execute
processCommand(cmd);
} else {
// no command - show preview if need
processDefault();
// wait for next command
synchronized (queue) {
if (queue.isEmpty()) {
queue.wait(100);
}
}
}
}
} catch (InterruptedException ex) {
}
}
public void exec(CameraCommand command) {
synchronized (queue) {
queue.add(command);
queue.notifyAll();
}
}
protected void processCommand(CameraCommand cmd) {
try {
cmd.exec(workerIndex, camera, lua);
} catch (Throwable ex) {
LOG.warn("Error execute camera command", ex);
}
}
protected void processDefault() {
ImageViewPane p = previewPanel;
if (p != null) {
try {
BufferedImage img = camera.getPreview();
p.displayImage(img, CHDK_ASPECT_WIDTH, CHDK_ASPECT_HEIGHT);
} catch (Exception ex) {
LOG.info("Error retrieve preview", ex);
}
}
}
public String getSerial() {
return serial;
}
}
}
| 9,471 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
ISourceDevice.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/devices/ISourceDevice.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan.devices;
import java.awt.Dimension;
import org.alex73.skarynka.scan.common.ImageViewPane;
/**
* Interface for one source device like cameras or scanner.
*
* @author Aleś Bułojčyk <alex73mail@gmail.com>
*/
public interface ISourceDevice {
boolean readyForScan();
boolean[] setPreviewPanels(ImageViewPane... panels);
int getZoom();
Dimension[] getImageSize();
int[] getRotations();
/**
* Some path can be null that means scan from this side should be skipped.
*/
String[] scan(String... pathsToOutput) throws Exception;
String getScannedFileExt();
/**
* Get device status text.
*/
String[] getStatus() throws Exception;
void close();
}
| 1,659 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
CHDKCameras.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/devices/CHDKCameras.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan.devices;
import java.awt.Dimension;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import org.alex73.UsbUtils;
import org.alex73.chdkptpj.camera.Camera;
import org.alex73.chdkptpj.lua.ChdkPtpJ;
import org.alex73.skarynka.scan.Context;
import org.alex73.skarynka.scan.Messages;
import org.alex73.skarynka.scan.ServiceException;
import org.alex73.skarynka.scan.common.ImageViewPane;
import org.alex73.skarynka.scan.devices.CameraWorker.CameraCommand;
import org.luaj.vm2.LuaTable;
import org.luaj.vm2.LuaValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* CHDK camera driver.
*
* @author Aleś Bułojčyk <alex73mail@gmail.com>
*/
public class CHDKCameras implements ISourceDevice {
private static Logger LOG = LoggerFactory.getLogger(CHDKCameras.class);
private final CameraWorker worker;
private boolean focused;
private int[] rotations;
private int zoom;
private final Properties props;
private final int imageWidth, imageHeight;
public CHDKCameras(List<Camera> cameras) throws Exception {
worker = new CameraWorker(cameras);
for (Camera c : cameras) {
String vendorid = UsbUtils.hex4(c.getDevice().getUsbDeviceDescriptor().idVendor());
String productid = UsbUtils.hex4(c.getDevice().getUsbDeviceDescriptor().idProduct());
String required = Context.getSettings().get("cameras-usbid");
if (required != null) {
if (!required.equals(vendorid + ":" + productid)) {
throw new ServiceException("CAMERA_WRONG_ID", required, vendorid + ":" + productid);
}
}
}
props = new Properties();
try (InputStream in = new FileInputStream(Context.getSettings().get("cameras-settings"))) {
props.load(in);
}
String imgWidth = props.getProperty("image.width");
String imgHeight = props.getProperty("image.height");
if (imgWidth == null) {
throw new Exception("image.width is not defined");
}
if (imgHeight == null) {
throw new Exception("image.height is not defined");
}
imageWidth = Integer.parseInt(imgWidth);
imageHeight = Integer.parseInt(imgHeight);
}
@Override
public boolean readyForScan() {
return focused;
}
@Override
public String getScannedFileExt() {
return "raw";
}
@Override
public String[] scan(String... pathsToOutput) throws Exception {
LOG.info("Scan to " + Arrays.toString(pathsToOutput));
long be=System.currentTimeMillis();
worker.exec(new CameraCommand() {
@Override
public void exec(int workerIndex, Camera camera, ChdkPtpJ lua) throws Exception {
String path = pathsToOutput[workerIndex];
if (path == null) {
return;
}
try {
LuaTable p = new LuaTable();
p.set("jpg", LuaValue.valueOf(true));
p.set("raw", LuaValue.valueOf(true));
p.set(1, LuaValue.valueOf(path));
lua.executeCliFunction("remoteshoot", p);
} catch (Throwable ex) {
new File(path + ".raw").delete();
new File(path + ".jpg").delete();
throw ex;
}
}
});
long af=System.currentTimeMillis();
LOG.info("Scan time: "+(af-be)+"ms");
return worker.getCamerasIds(props);
}
@Override
public String[] getStatus() throws Exception {
LOG.trace("getStatus()");
String[] result = new String[worker.getCamerasCount()];
worker.exec(new CameraCommand() {
@Override
public void exec(int workerIndex, Camera camera, ChdkPtpJ lua) throws Exception {
Object tOpt = camera.executeLua("get_temperature(0)");
Object tSens = camera.executeLua("get_temperature(1)");
result[workerIndex] = Messages.getString("CAMERA_INFO", tOpt, tSens);
}
});
return result;
}
public void connect() throws Exception {
LOG.info("Connect to cameras...");
worker.exec(new CameraCommand() {
@Override
public void exec(Camera camera) throws Exception {
camera.setRecordMode();
StringBuilder s = new StringBuilder();
s.append("call_event_proc('UI.CreatePublic')\n");
for (Map.Entry<String, String> en : (Set<Map.Entry<String, String>>) (Set) props.entrySet()) {
if (en.getKey().startsWith("prop.")) {
String k = en.getKey().substring(5);
if (en.getValue().trim().startsWith("-")) {
// skip values less than zero - it's impossible to set they
continue;
}
s.append("if call_event_proc('PTM_SetCurrentItem'," + k + "," + en.getValue()
+ ") ~= 0 then\n");
s.append(" error('Error set " + k + "')\n");
s.append("end\n");
}
}
for (Map.Entry<String, String> en : (Set<Map.Entry<String, String>>) (Set) props.entrySet()) {
if (en.getKey().startsWith("prop.")) {
String k = en.getKey().substring(5);
String v = en.getValue().trim();
if (v.startsWith("-")) {
v = Integer.toString(65536 + Integer.parseInt(v));
}
s.append("if call_event_proc('PTM_GetCurrentItem'," + k + ") ~= " + v + " then\n");
s.append(" error('Wrong value in the " + k + ": expected is " + v
+ " but really is '..call_event_proc('PTM_GetCurrentItem'," + k + "))\n");
s.append("end\n");
}
}
camera.executeLua(s.toString());
}
});
}
@Override
public void close() {
LOG.trace("disconnect()");
try {
worker.exec(new CameraCommand() {
@Override
public void exec(Camera camera) {
try {
camera.disconnect();
} catch (Exception ex) {
LOG.warn("Error disconnect from camera", ex);
}
}
});
} catch (Exception ex) {
}
}
@Override
public int getZoom() {
return zoom;
}
@Override
public Dimension[] getImageSize() {
Dimension[] sizes = new Dimension[2];
sizes[0] = new Dimension(imageWidth, imageHeight);
sizes[1] = new Dimension(imageWidth, imageHeight);
return sizes;
}
public int getCurrentZoom() throws Exception {
LOG.trace("getZoom()");
AtomicInteger result = new AtomicInteger();
worker.exec(new CameraCommand() {
@Override
public void exec(Camera camera) throws Exception {
int zoom = camera.getScripting().get_zoom();
result.set(zoom);
}
});
return result.get();
}
public void setZoom(int zoom) throws Exception {
LOG.trace("setZoom()");
this.zoom = zoom;
worker.exec(new CameraCommand() {
@Override
public void exec(Camera camera) throws Exception {
camera.getScripting().set_zoom(zoom);
}
});
}
public int getMaxZoom() throws Exception {
LOG.trace("getMaxZoom()");
AtomicInteger result = new AtomicInteger();
worker.exec(new CameraCommand() {
@Override
public void exec(Camera camera) throws Exception {
int maxZoom = camera.getScripting().get_zoom_steps() - 1;
result.set(maxZoom);
}
});
return result.get();
}
public int[] getRotations() {
return rotations;
}
public void setRotations(int... rotations) {
this.rotations = rotations;
}
public List<Integer> focus() throws Exception {
LOG.info("Focus cameras...");
List<Integer> result = Collections.synchronizedList(new ArrayList<>());
worker.exec(new CameraCommand() {
@Override
public void exec(Camera camera) throws Exception {
LOG.info("SdOverMode = " + camera.getScripting().get_sd_over_modes());
String manualFocusDistance = Context.getSettings().get("cameras-manual-focus-distance");
if (manualFocusDistance != null) {
int distance = Integer.parseInt(manualFocusDistance);
camera.executeLua("set_aflock(0); set_focus(" + distance
+ "); sleep(500); press (\"shoot_half\"); sleep(1000); set_aflock(1); release (\"shoot_half\"); sleep(500);");
} else {
// autofocus lock
camera.executeLua(
"set_aflock(0); press (\"shoot_half\"); sleep(5000); set_aflock(1); release (\"shoot_half\");");
}
LOG.info("Camera " + camera.getDevice().getSerialNumberString() + " focused");
LOG.info("FocusMode = " + camera.getScripting().get_focus_mode());
LOG.info("FocusDistance(mm) = " + camera.getScripting().get_focus());
LOG.info("FocusState = " + camera.getScripting().get_focus_state());
LOG.info("DofInfo :\n" + camera.getScripting().get_dofinfo());
result.add(camera.getScripting().get_focus());
}
});
focused = true;
LOG.info("Cameras focused on " + result);
return result;
}
public boolean[] setPreviewPanels(ImageViewPane... panels) {
return worker.setPreviewPanels(panels);
}
public void swap() {
worker.swap();
}
public Properties getCamerasProperties() {
return props;
}
// public void o() {
// System.out.println("get_av96 = " + cam.executeLuaQuery("return get_av96();"));
// System.out.println("get_bv96 = " + cam.executeLuaQuery("return get_bv96();"));
// System.out.println("get_ev = " + cam.executeLuaQuery("return get_ev();"));
// System.out.println("get_iso_mode = " + cam.executeLuaQuery("return get_iso_mode();"));
// // System.out.println("get_live_histo = "+cam.executeLuaQuery("return get_live_histo ();"));
//
// System.out.println("Temp(optical) = " + cam.executeLuaQuery("return get_temperature(0);"));
// System.out.println("Temp(CCD) = " + cam.executeLuaQuery("return get_temperature(1);"));
// System.out.println("Temp(battery) = " + cam.executeLuaQuery("return get_temperature(2);"));
//
// System.out.println("get_free_disk_space(MiB) = "
// + ((int) cam.executeLuaQuery("return get_free_disk_space();") / 1024));
//
// cam.executeLuaQuery("return shoot();");
// }
}
| 12,532 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
Stub.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/devices/Stub.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan.devices;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import javax.imageio.ImageIO;
import org.alex73.skarynka.scan.Messages;
import org.alex73.skarynka.scan.common.ImageViewPane;
/**
* Stub device. It uses predefined images from files.
*
* @author Aleś Bułojčyk <alex73mail@gmail.com>
*/
public class Stub implements ISourceDevice {
private final String dir;
private ImageViewPane[] preview;
private int c;
public Stub(String dir) {
this.dir = dir;
}
@Override
public void close() {
}
@Override
public boolean[] setPreviewPanels(ImageViewPane... panels) {
this.preview = panels;
showPreview();
return new boolean[] { true, true };
}
void showPreview() {
int p = c + 1;
try {
BufferedImage p1 = ImageIO.read(new File("/home/alex/MyShare-Temp/c/c1/" + p + ".JPG"));
BufferedImage p2 = ImageIO.read(new File("/home/alex/MyShare-Temp/c/c2/" + p + ".JPG"));
preview[0].displayImage(p1, 1, 1);
preview[1].displayImage(p2, 1, 1);
} catch (Exception ex) {
}
}
@Override
public int getZoom() {
return 0;
}
@Override
public Dimension[] getImageSize() {
Dimension[] sizes = new Dimension[2];
sizes[0] = new Dimension(5248, 3920);
sizes[1] = new Dimension(5248, 3920);
return sizes;
}
@Override
public int[] getRotations() {
return new int[] { 3, 1 };
}
@Override
public String getScannedFileExt() {
return "CRW";
}
@Override
public String[] scan(String... pathsToOutput) throws Exception {
c++;
Files.copy(Paths.get("/home/alex/MyShare-Temp/c/c1/" + c + ".JPG"),
Paths.get(pathsToOutput[0] + ".JPG"), StandardCopyOption.REPLACE_EXISTING);
Files.copy(Paths.get("/home/alex/MyShare-Temp/c/c1/" + c + ".CRW"),
Paths.get(pathsToOutput[0] + ".CRW"), StandardCopyOption.REPLACE_EXISTING);
Files.copy(Paths.get("/home/alex/MyShare-Temp/c/c2/" + c + ".JPG"),
Paths.get(pathsToOutput[1] + ".JPG"), StandardCopyOption.REPLACE_EXISTING);
Files.copy(Paths.get("/home/alex/MyShare-Temp/c/c2/" + c + ".CRW"),
Paths.get(pathsToOutput[1] + ".CRW"), StandardCopyOption.REPLACE_EXISTING);
showPreview();
return new String[] { "s1", "s2" };
}
@Override
public String[] getStatus() throws Exception {
return new String[] { Messages.getString("CAMERA_INFO", 20, 20),
Messages.getString("CAMERA_INFO", 20, 20) };
}
@Override
public boolean readyForScan() {
return true;
}
}
| 3,803 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
Wizard.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/wizards/Wizard.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan.wizards;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.URL;
import java.util.Dictionary;
import java.util.Hashtable;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingWorker;
import org.alex73.skarynka.scan.DataStorage;
import org.alex73.skarynka.scan.Messages;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class Wizard extends JDialog {
private static Logger LOG = LoggerFactory.getLogger(Wizard.class);
private JTextPane area;
private JScrollPane sc;
private JButton btnNext;
private JButton btnCancel;
private Runnable next;
private String nextText;
public Wizard(String title) {
super(DataStorage.mainFrame, title, true);
getContentPane().setLayout(new BorderLayout());
area = new JTextPane();
area.setEditable(false);
area.setContentType("text/html");
sc = new JScrollPane(area);
getContentPane().add(sc, BorderLayout.CENTER);
JPanel buttonsPanel = new JPanel(new FlowLayout());
getContentPane().add(buttonsPanel, BorderLayout.SOUTH);
btnNext = new JButton(Messages.getString("WIZARD_NEXT"));
buttonsPanel.add(btnNext);
btnCancel = new JButton(Messages.getString("CANCEL"));
buttonsPanel.add(btnCancel);
setSize(1000, 800);
setLocationRelativeTo(DataStorage.mainFrame);
setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
if (btnCancel.isEnabled()) {
cancel();
}
}
});
btnNext.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
executeNext();
}
});
btnCancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cancel();
}
});
}
protected void addImage(String url, String imagePath) {
Dictionary<URL, Image> cache = (Dictionary<URL, Image>) area.getDocument().getProperty("imageCache");
if (cache == null) {
cache = new Hashtable<URL, Image>();
area.getDocument().putProperty("imageCache", cache);
}
try {
Image image = ImageIO.read(Wizard.class.getResource(imagePath));
cache.put(new URL(url), image);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
protected void showStep(String text, String nextText, Runnable clickNext) {
next = clickNext;
this.nextText = nextText;
area.setText(text);
sc.scrollRectToVisible(new Rectangle());
if (!isVisible()) {
setVisible(true);
}
}
protected void showLastStep(String text) {
btnNext.setText(Messages.getString("OK"));
btnCancel.setVisible(false);
next = new Runnable() {
@Override
public void run() {
done();
dispose();
}
};
area.setText(text);
sc.scrollRectToVisible(new Rectangle());
}
protected void executeNext() {
btnNext.setEnabled(false);
btnCancel.setEnabled(false);
area.setText(nextText);
sc.scrollRectToVisible(new Rectangle());
new SwingWorker<Object, Object>() {
@Override
protected Object doInBackground() throws Exception {
next.run();
return null;
}
@Override
protected void done() {
try {
get();
btnNext.setEnabled(true);
btnCancel.setEnabled(true);
} catch (Throwable ex) {
LOG.error("Error in wizard", ex);
area.setText("ERROR: " + ex.getMessage());
}
}
}.execute();
}
protected String getPackagePath() {
String p = '/' + this.getClass().getPackage().getName();
p = p.replace('.', '/');
return p;
}
abstract protected void cancel();
abstract protected void done();
}
| 5,683 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
CameraBadPixelsWizard.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/wizards/camera_badpixels/CameraBadPixelsWizard.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan.wizards.camera_badpixels;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import javax.imageio.ImageIO;
import org.alex73.chdkptpj.camera.Camera;
import org.alex73.chdkptpj.camera.CameraFactory;
import org.alex73.chdkptpj.lua.ChdkPtpJ;
import org.alex73.skarynka.scan.Context;
import org.alex73.skarynka.scan.DataStorage;
import org.alex73.skarynka.scan.Messages;
import org.alex73.skarynka.scan.ServiceException;
import org.alex73.skarynka.scan.wizards.Wizard;
import org.apache.commons.io.IOUtils;
import org.luaj.vm2.LuaBoolean;
import org.luaj.vm2.LuaTable;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Bad/hot pixels detection wizard.
*
* By https://www.cybercom.net/~dcoffin/dcraw/.badpixels: Always use "dcraw -d -j -t 0" when locating bad
* pixels!! Format is: pixel column, pixel row, UNIX time of death
*
* By http://chdk.wikia.com/wiki/CHDK_1.3.0_User_Manual: To create this file, you will need to capture a
* "dark frame" image by shooting an image with the lens completely capped. For shutter speeds longer than 2
* seconds, you may want to keep a collection of "dark frame" image on hand for each exposure length that you
* will be using in the future, as more warm and hot-pixels appear with extended shutter speeds.
*/
public class CameraBadPixelsWizard extends Wizard {
private static Logger LOG = LoggerFactory.getLogger(CameraBadPixelsWizard.class);
private Camera camera;
private ChdkPtpJ lua;
private StringBuilder out = new StringBuilder();
private long date = System.currentTimeMillis();
public CameraBadPixelsWizard() {
super(Messages.getString("CAMERA_BADPIXELS_TITLE"));
addImage("file://camera-on.png", getPackagePath() + "/camera-on.png");
addImage("file://camera-power.png", getPackagePath() + "/camera-power.png");
addImage("file://camera-usb.png", getPackagePath() + "/camera-usb.png");
}
public void process() {
if (DataStorage.device != null) {
DataStorage.device.close();
DataStorage.device = null;
}
showStep(Messages.getFile(getPackagePath() + "/instruction-connect.html"),
Messages.getString("CAMERA_INIT_PROCESS"), scanIntro);
}
Runnable scanIntro = new Runnable() {
@Override
public void run() {
try {
List<Camera> cameras = CameraFactory.findCameras();
switch (cameras.size()) {
case 0:
LOG.info("No cameras");
throw new ServiceException("CHDK_NO_CAMERAS");
case 1:
LOG.info("One camera");
camera = cameras.get(0);
break;
default:
LOG.info("Many cameras");
throw new ServiceException("CHDK_TOO_MANY_CAMERAS");
}
camera.connect();
camera.setRecordMode();
lua = new ChdkPtpJ(camera, "lua-orig");
showStep(Messages.getFile(getPackagePath() + "/instruction-black.html"),
Messages.getString("CAMERA_BADPIXELS_PROCESS"), scanBlack);
} catch (ServiceException ex) {
String m = Messages.getFile(getPackagePath() + "/instruction-connect-error.html");
m = m.replace("{0}", ex.getMessage());
showLastStep(m);
} catch (Throwable ex) {
LOG.error("Error find cameras", ex);
String m = Messages.getFile(getPackagePath() + "/instruction-connect-error.html");
m = m.replace("{0}", ex.getClass().getSimpleName() + ": " + ex.getMessage());
showLastStep(m);
}
}
};
Runnable scanBlack = new Runnable() {
@Override
public void run() {
String path = Context.getBookDir();
try {
LuaTable p = new LuaTable();
p.set("jpg", LuaValue.valueOf(false));
p.set("raw", LuaValue.valueOf(true));
p.set("tv", LuaValue.valueOf(1));
p.set("sd", LuaValue.valueOf("200mm"));
shoot(p, path + "/black1");
shoot(p, path + "/black2");
shoot(p, path + "/black3");
showStep(Messages.getFile(getPackagePath() + "/instruction-white.html"),
Messages.getString("CAMERA_BADPIXELS_PROCESS"), scanWhite);
} catch (Exception ex) {
LOG.warn("Error scan for badpixels", ex);
String m = Messages.getFile(getPackagePath() + "/instruction-error.html");
m = m.replace("{0}", ex.getClass().getSimpleName() + ": " + ex.getMessage());
showLastStep(m);
}
}
};
Runnable scanWhite = new Runnable() {
@Override
public void run() {
String path = Context.getBookDir();
try {
LuaTable p = new LuaTable();
p.set("jpg", LuaValue.valueOf(false));
p.set("raw", LuaValue.valueOf(true));
p.set("tv", LuaValue.valueOf(5));
p.set("sd", LuaValue.valueOf("200mm"));
shoot(p, path + "/white1");
shoot(p, path + "/white2");
shoot(p, path + "/white3");
finish();
} catch (Exception ex) {
LOG.warn("Error scan for badpixels", ex);
String m = Messages.getFile(getPackagePath() + "/instruction-error.html");
m = m.replace("{0}", ex.getClass().getSimpleName() + ": " + ex.getMessage());
showLastStep(m);
}
}
};
void finish() {
try {
String badBlack = calc(128, 256, read( "black1.raw"), read( "black2.raw"),
read( "black3.raw"));
String badWhite = calc(0, 128, read( "white1.raw"), read( "white2.raw"),
read( "white3.raw"));
if (badBlack == null || badWhite == null) {
String m = Messages.getFile(getPackagePath() + "/instruction-error.html");
m = m.replace("{0}", out.toString());
showLastStep(m);
} else {
out.setLength(0);
out.append(Messages.getString("CAMERA_BADPIXELS_RESULT",
camera.getDevice().getSerialNumberString().trim())).append("\n");
out.append("=======================================\n");
out.append("# hot pixels from black image\n");
out.append(badBlack);
out.append("# bad pixels from white image\n");
out.append(badWhite);
String m = Messages.getFile(getPackagePath() + "/instruction-done.html");
m = m.replace("{0}", out.toString());
showLastStep(m);
}
} catch (Throwable ex) {
LOG.warn("Error scan for badpixels", ex);
String m = Messages.getFile(getPackagePath() + "/instruction-error.html");
m = m.replace("{0}", ex.getClass().getSimpleName() + ": " + ex.getMessage());
showLastStep(m);
}
}
@Override
protected void done() {
}
@Override
public void cancel() {
dispose();
}
void shoot(LuaTable p, String file) throws Exception {
p.set(1, LuaValue.valueOf(file));
Varargs r = lua.executeCliFunction("remoteshoot", p);
r.arg1().checkboolean();
if (!((LuaBoolean) r.arg1()).booleanValue()) {
throw new Exception(r.arg(2).tojstring());
}
}
BufferedImage read(String file) throws Exception {
out.append("\n");
out.append(Messages.getString("CAMERA_BADPIXELS_ANALYZE", file)).append("\n");
String fileBMP = file.replaceAll("\\.[a-zA-Z0-9]{3}", ".bmp");
String cmdo= Context.getSettings().get("path_dcraw")+" -c -d -j -t 0 -W "+ file+" | "+Context.getSettings().get("path_convert")+" - "+fileBMP;
String[] cmda;
switch (Context.thisOS) {
case LINUX:
cmda = new String[] { "nice", "ionice", "-c3", "sh", "-c", cmdo.toString() };
break;
case WINDOWS:
cmda = new String[] { "cmd.exe", "/c", cmdo.toString() };
break;
default:
throw new Exception("Unknown OS");
}
LOG.debug("Execute : " + cmdo);
Process process = Runtime.getRuntime().exec(cmda, null, new File(Context.getBookDir()));
int r = process.waitFor();
LOG.debug("Execution result: " + r);
if (r != 0) {
String err = IOUtils.toString(process.getErrorStream(),
Context.getSettings().get("command_charset"));
throw new Exception("Error execution : " + r + " / " + err);
}
return ImageIO.read(new File(Context.getBookDir(), fileBMP));
}
static final int THRESHOLD = 128;
String calc(int cFrom, int cTo, BufferedImage... images) {
for (int i = 1; i < images.length; i++) {
if (images[i].getWidth() != images[0].getWidth()
|| images[i].getHeight() != images[0].getHeight()) {
throw new RuntimeException("Wrong images size");
}
}
StringBuilder dump = new StringBuilder();
int count = 0;
for (int x = 0; x < images[0].getWidth(); x++) {
for (int y = 0; y < images[0].getHeight(); y++) {
boolean bad = false;
for (int i = 0; i < images.length; i++) {
int rgb = images[i].getRGB(x, y);
int r = rgb & 0xff;
int g = (rgb >> 8) & 0xff;
int b = (rgb >> 16) & 0xff;
int c = (r + g + b) / 3;
if (c >= cFrom && c <= cTo) {
bad = true;
count++;
break;
}
}
if (bad && count <= 2000) {
dump.append(" " + coord(x) + " " + coord(y) + " " + date + " #");
for (int i = 0; i < images.length; i++) {
int rgb = images[i].getRGB(x, y);
int r = rgb & 0xff;
int g = (rgb >> 8) & 0xff;
int b = (rgb >> 16) & 0xff;
int c = (r + g + b) / 3;
dump.append(" " + c);
}
dump.append("\n");
}
}
}
if (count > 2000) {
// more than 0.1%
out.append(Messages.getString("CAMERA_BADPIXELS_TOO_MANY", count)).append("\n");
return null;
}
return dump.toString();
}
String coord(int p) {
String r = Integer.toString(p);
return " ".substring(r.length()) + r;
}
}
| 12,119 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
CameraInitWizard.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/wizards/camera_init/CameraInitWizard.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan.wizards.camera_init;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.alex73.chdkptpj.camera.Camera;
import org.alex73.chdkptpj.camera.CameraFactory;
import org.alex73.skarynka.scan.DataStorage;
import org.alex73.skarynka.scan.Messages;
import org.alex73.skarynka.scan.ServiceException;
import org.alex73.skarynka.scan.devices.CHDKCameras;
import org.alex73.skarynka.scan.wizards.Wizard;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.usb4java.javax.UsbHacks;
public class CameraInitWizard extends Wizard {
private static Logger LOG = LoggerFactory.getLogger(CameraInitWizard.class);
private CHDKCameras dev;
public CameraInitWizard() {
super(Messages.getString("CAMERA_INIT_TITLE"));
addImage("file://camera-on.png", getPackagePath() + "/camera-on.png");
addImage("file://camera-power.png", getPackagePath() + "/camera-power.png");
addImage("file://camera-usb.png", getPackagePath() + "/camera-usb.png");
}
public void process() {
if (DataStorage.device != null) {
DataStorage.device.close();
DataStorage.device = null;
}
showStep(Messages.getFile(getPackagePath() + "/instruction.html"),
Messages.getString("CAMERA_INIT_PROCESS"), initCameras);
}
Runnable initCameras = new Runnable() {
@Override
public void run() {
try {
boolean oneBus = false;
boolean differentCameras = false;
String manufacturer = null, product = null;
Set<Integer> usedBuses = new TreeSet<>();
List<Camera> cameras = CameraFactory.findCameras();
for (Camera c : cameras) {
int bus = UsbHacks.getDeviceId(c.getDevice()).getBusNumber();
if (!usedBuses.add(bus)) {
oneBus = true;
}
if (manufacturer == null || product == null) {
manufacturer = c.getDevice().getManufacturerString();
product = c.getDevice().getProductString();
} else if (!StringUtils.equals(manufacturer, c.getDevice().getManufacturerString())
|| !StringUtils.equals(product, c.getDevice().getProductString())) {
differentCameras = true;
}
}
String m = Messages.getFile(getPackagePath() + "/instruction-done.html");
switch (cameras.size()) {
case 0:
LOG.info("No cameras");
throw new ServiceException("CHDK_NO_CAMERAS");
case 1:
LOG.info("One camera");
m = m.replace("{0}", "Падлучана адна камэра.");
break;
case 2:
LOG.info("Two cameras");
m = m.replace("{0}", "Падлучана дзьве камэры.");
break;
default:
LOG.info("Many cameras");
throw new ServiceException("CHDK_TOO_MANY_CAMERAS");
}
m = m.replace("{1}",
oneBus ? "Камэры падлучаныя да адной USB шыны. Гэта зьменьшыць хуткасьць сканаваньня старонак недзе на сэкунду."
: "");
m = m.replace("{2}", differentCameras
? "Розныя мадэлі камэр. Вельмі пажадана выкарыстоўваць аднолькавыя камэры." : "");
dev = new CHDKCameras(cameras);
dev.connect();
showLastStep(m);
} catch (ServiceException ex) {
String m = Messages.getFile(getPackagePath() + "/instruction-error.html");
m = m.replace("{0}", ex.getMessage());
showLastStep(m);
} catch (Throwable ex) {
LOG.error("Error find camera", ex);
String m = Messages.getFile(getPackagePath() + "/instruction-error.html");
m = m.replace("{0}", ex.getClass().getSimpleName() + ": " + ex.getMessage());
showLastStep(m);
}
}
};
@Override
protected void done() {
DataStorage.device = dev;
DataStorage.focused = false;
}
@Override
public void cancel() {
dispose();
}
}
| 5,620 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
CameraFocusController.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/wizards/camera_focus/CameraFocusController.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan.wizards.camera_focus;
import java.awt.GridBagConstraints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingWorker;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.alex73.skarynka.scan.DataStorage;
import org.alex73.skarynka.scan.Messages;
import org.alex73.skarynka.scan.common.ImageViewPane;
import org.alex73.skarynka.scan.devices.CHDKCameras;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CameraFocusController {
private static Logger LOG = LoggerFactory.getLogger(CameraFocusController.class);
private CHDKCameras cameras;
private CameraFocusPanel dialog;
private ImageViewPane previewLeft, previewRight;
private SpinnerNumberModel model;
public void show() {
try {
cameras = (CHDKCameras) DataStorage.device;
dialog = new CameraFocusPanel(DataStorage.mainFrame, true);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.btnClose.setEnabled(false);
dialog.btnClose.addActionListener(closeActionListener);
dialog.btnFocus.addActionListener(focusActionListener);
dialog.btnRotateLeft.addActionListener(rotateLeft);
dialog.btnRotateRight.addActionListener(rotateRight);
dialog.btnSwap.addActionListener(swap);
int maxZoom = cameras.getMaxZoom();
int currentZoom = cameras.getZoom();
int step = Math.round(maxZoom * 0.1f);
dialog.lblZoom.setText(Messages.getString("CAMERA_FOCUS_ZOOM", maxZoom));
// set equals zoom for all cameras
cameras.setZoom(currentZoom);
model = new SpinnerNumberModel(currentZoom, 0, maxZoom, step);
model.addChangeListener(zoomChangeListener);
dialog.spZoom.setModel(model);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridy = 1;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.gridx = 0;
previewLeft = new ImageViewPane();
dialog.getContentPane().add(previewLeft, gbc);
gbc.gridx = 1;
previewRight = new ImageViewPane();
dialog.getContentPane().add(previewRight, gbc);
cameras.setPreviewPanels(previewLeft, previewRight);
dialog.setSize(1000, 800);
dialog.setLocationRelativeTo(DataStorage.mainFrame);
dialog.setVisible(true);
} catch (Throwable ex) {
LOG.warn("Error initialize focus wizard", ex);
JOptionPane.showMessageDialog(DataStorage.mainFrame, "Error: " + ex.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
}
}
ActionListener rotateLeft = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
previewLeft.setRotation((previewLeft.getRotation() + 1) % 4);
}
};
ActionListener rotateRight = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
previewRight.setRotation((previewRight.getRotation() + 1) % 4);
}
};
ActionListener swap = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cameras.swap();
}
};
ChangeListener zoomChangeListener = new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
try {
int zoom = (int) model.getValue();
cameras.setZoom(zoom);
} catch (Exception ex) {
LOG.warn("Error focus camera",ex);
JOptionPane.showMessageDialog(
DataStorage.mainFrame,
Messages.getString("ERROR_FOCUS", ex.getClass().getName(), ex.getMessage(),
Messages.getString("ERROR_TITLE"), JOptionPane.ERROR_MESSAGE));
}
}
};
ActionListener closeActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
};
ActionListener focusActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dialog.lblStatus.setText(Messages.getString("CAMERA_FOCUS_PROCESSING"));
new SwingWorker<List<Integer>, Object>() {
@Override
protected List<Integer> doInBackground() throws Exception {
cameras.setRotations(previewLeft.getRotation(), previewRight.getRotation());
return cameras.focus();
}
protected void done() {
try {
List<Integer> distances = get();
dialog.lblStatus.setText(Messages.getString("CAMERA_FOCUS_DISTANCE",
distances.toString()));
dialog.btnClose.setEnabled(true);
} catch (Exception ex) {
dialog.lblStatus.setText(Messages.getString("CAMERA_FOCUS_ERROR", ex.getMessage()));
}
}
}.execute();
}
};
}
| 6,455 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
CameraFocusPanel.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/wizards/camera_focus/CameraFocusPanel.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan.wizards.camera_focus;
import org.alex73.skarynka.scan.Messages;
/**
*
* @author alex
*/
public class CameraFocusPanel extends javax.swing.JDialog {
/**
* Creates new form CameraFocusWizard
*/
public CameraFocusPanel(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
jPanel1 = new javax.swing.JPanel();
lblZoom = new javax.swing.JLabel();
spZoom = new javax.swing.JSpinner();
btnFocus = new javax.swing.JButton();
btnClose = new javax.swing.JButton();
lblStatus = new javax.swing.JLabel();
btnRotateLeft = new javax.swing.JButton();
btnSwap = new javax.swing.JButton();
btnRotateRight = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setLayout(new java.awt.GridBagLayout());
jPanel1.setLayout(new java.awt.GridBagLayout());
lblZoom.setText(Messages.getString("CAMERA_FOCUS_ZOOM")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
jPanel1.add(lblZoom, gridBagConstraints);
spZoom.setModel(new javax.swing.SpinnerNumberModel());
spZoom.setMinimumSize(new java.awt.Dimension(70, 20));
spZoom.setPreferredSize(new java.awt.Dimension(70, 20));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
jPanel1.add(spZoom, gridBagConstraints);
btnFocus.setText(Messages.getString("CAMERA_FOCUS_FOCUS")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
jPanel1.add(btnFocus, gridBagConstraints);
btnClose.setText(Messages.getString("CAMERA_FOCUS_CLOSE")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
jPanel1.add(btnClose, gridBagConstraints);
lblStatus.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblStatus.setText(" ");
lblStatus.setToolTipText("");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
jPanel1.add(lblStatus, gridBagConstraints);
btnRotateLeft.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/alex73/skarynka/scan/wizards/camera_focus/rotate.png"))); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
jPanel1.add(btnRotateLeft, gridBagConstraints);
btnSwap.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/alex73/skarynka/scan/wizards/camera_focus/swap.png"))); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
jPanel1.add(btnSwap, gridBagConstraints);
btnRotateRight.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/alex73/skarynka/scan/wizards/camera_focus/rotate.png"))); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
jPanel1.add(btnRotateRight, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
getContentPane().add(jPanel1, gridBagConstraints);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(CameraFocusPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CameraFocusPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CameraFocusPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CameraFocusPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
CameraFocusPanel dialog = new CameraFocusPanel(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
public javax.swing.JButton btnClose;
public javax.swing.JButton btnFocus;
public javax.swing.JButton btnRotateLeft;
public javax.swing.JButton btnRotateRight;
public javax.swing.JButton btnSwap;
public javax.swing.JPanel jPanel1;
public javax.swing.JLabel lblStatus;
public javax.swing.JLabel lblZoom;
public javax.swing.JSpinner spZoom;
// End of variables declaration//GEN-END:variables
}
| 8,483 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
HIDScanController.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/hid/HIDScanController.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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.alex73.skarynka.scan.hid;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import javax.swing.SwingUtilities;
import javax.usb.UsbConst;
import javax.usb.UsbDevice;
import javax.usb.UsbEndpoint;
import javax.usb.UsbInterface;
import javax.usb.UsbPipe;
import javax.usb.util.UsbUtil;
import org.alex73.UsbUtils;
import org.alex73.skarynka.scan.Context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Driver for HID (mouse or pedal) devices for initiate scan.
*
* usb4java works with HID devices not so good. Usually, it throws exception after several usages. Need to
* change to usb HID implementation or find other way. Before that, 'hidscan-keys' parameter usage
* recommended.
*
* @author Aleś Bułojčyk <alex73mail@gmail.com>
*/
public class HIDScanController extends Thread {
private static Logger LOG = LoggerFactory.getLogger(HIDScanController.class);
protected UsbPipe usbPipe;
protected String hidDeviceUsbId;
protected ScanListener testListener;
private long lastSendTime;
private boolean finished;
public HIDScanController(String hidDeviceUsbId, String interfaceProtocol) {
install(hidDeviceUsbId, interfaceProtocol);
}
public boolean isConnected() {
return usbPipe != null;
}
public String getHIDDeviceUsbId() {
return hidDeviceUsbId;
}
public void setTestListener(ScanListener testListener) {
this.testListener = testListener;
}
@Override
public void run() {
if (usbPipe == null) {
return;
}
byte[] buffer = new byte[UsbUtil
.unsignedInt(usbPipe.getUsbEndpoint().getUsbEndpointDescriptor().wMaxPacketSize())];
while (!finished) {
try {
Arrays.fill(buffer, (byte) 0);
int length = usbPipe.syncSubmit(buffer);
if (length > 0) {
if (lastSendTime + 1000 > System.currentTimeMillis()) {
// one-second delay before next sending. Used because some definces sends many equals
// packets
continue;
}
lastSendTime = System.currentTimeMillis();
if (testListener != null) {
displayKey(buffer);
} else {
sendKey(buffer);
}
}
} catch (Throwable ex) {
LOG.error("Unable to receive data from HID device : ", ex);
}
}
}
private void displayKey(byte[] buffer) throws Exception {
String k = getConfigKey(buffer);
String button = Context.getSettings().get(k);
if (button == null) {
button = "<" + k.replace("hidscan-button.", "") + ">";
}
testListener.pressed(button);
}
private void sendKey(byte[] buffer) {
// Get key code from config.xml by data buffer.
String configKey = getConfigKey(buffer);
String key = Context.getSettings().get(configKey);
int keyCode = getKeyCode(key);
if (keyCode != 0) {
LOG.trace("HID device keyCode " + keyCode);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
Robot robot = new Robot();
robot.keyPress(keyCode);
robot.keyRelease(keyCode);
} catch (Throwable ex) {
LOG.error("Can't send key to application : ", ex);
}
}
});
}
}
/**
* Convert 'VK_..' key name into int value.
*/
public static int getKeyCode(String key) {
try {
if (key == null) {
return 0;
}
Field f = KeyEvent.class.getField(key);
if (f == null) {
LOG.error("Field " + key + " not defined");
return 0;
}
return f.getInt(KeyEvent.class);
} catch (Throwable ex) {
LOG.error("Can't get key : ", ex);
return 0;
}
}
private String getConfigKey(byte[] data) {
StringBuilder s = new StringBuilder(100);
s.append("hidscan-button");
for (int i = 0; i < data.length; i++) {
s.append('.').append(Integer.toHexString(data[i]));
}
return s.toString();
}
private void dumpInfo(String hidDeviceUsbId) {
try {
for (UsbDevice dev : UsbUtils.listAllUsbDevices()) {
String usbId = UsbUtils.hex4(dev.getUsbDeviceDescriptor().idVendor()) + ':'
+ UsbUtils.hex4(dev.getUsbDeviceDescriptor().idProduct());
if (hidDeviceUsbId.equals(usbId)) {
LOG.info("Found USB device: " + hidDeviceUsbId);
for (UsbInterface uintf : (List<? extends UsbInterface>) dev.getActiveUsbConfiguration()
.getUsbInterfaces()) {
LOG.info(" Found USB interface: " + hidDeviceUsbId + " with protocol="
+ uintf.getUsbInterfaceDescriptor().bInterfaceProtocol());
for (UsbEndpoint e : (List<UsbEndpoint>) uintf.getUsbEndpoints()) {
LOG.info(" Found USB endpoint with type=" + e.getType() + " and direction="
+ e.getDirection());
}
}
}
}
} catch (Throwable ex) {
LOG.info("Error dump usb devices", ex);
}
}
private void install(String hidDeviceUsbId, String interfaceProtocol) {
dumpInfo(hidDeviceUsbId);
UsbInterface u = null;
try {
UsbDevice d = null;
for (UsbDevice dev : UsbUtils.listAllUsbDevices()) {
String usbId = UsbUtils.hex4(dev.getUsbDeviceDescriptor().idVendor()) + ':'
+ UsbUtils.hex4(dev.getUsbDeviceDescriptor().idProduct());
if (hidDeviceUsbId.equals(usbId)) {
d = dev;
break;
}
}
if (d == null) {
LOG.info("There is no HID Scan defined device, driver will not be installed");
return;
}
List<? extends UsbInterface> interfaces = d.getActiveUsbConfiguration().getUsbInterfaces();
if (interfaces.isEmpty()) {
LOG.info("HID Scan device doesn't contain interfaces, driver will not be installed");
return;
}
for (UsbInterface uintf : interfaces) {
u = uintf;
if (interfaceProtocol != null) {
int proto = u.getUsbInterfaceDescriptor().bInterfaceProtocol();
if (!interfaceProtocol.equals(Integer.toString(proto))) {
continue;
}
}
u.claim();
UsbEndpoint usbEndpoint = null;
for (UsbEndpoint e : (List<UsbEndpoint>) u.getUsbEndpoints()) {
if (UsbConst.ENDPOINT_TYPE_INTERRUPT == e.getType()
&& UsbConst.ENDPOINT_DIRECTION_IN == e.getDirection()) {
usbEndpoint = e;
break;
}
}
if (usbEndpoint == null) {
LOG.info("There is no endpoint in HID Scan, driver will not be installed");
return;
}
usbPipe = usbEndpoint.getUsbPipe();
usbPipe.open();
this.hidDeviceUsbId = hidDeviceUsbId;
}
if (usbPipe == null) {
LOG.info("There is no interface in HID Scan, driver will not be installed");
return;
}
} catch (Throwable ex) {
LOG.info("Error install HID Scan driver", ex);
usbPipe = null;
if (u != null) {
try {
u.release();
} catch (Throwable e) {
}
}
}
}
public void finish() {
finished = true;
if (usbPipe != null) {
try {
usbPipe.abortAllSubmissions();
} catch (Throwable ex) {
}
try {
usbPipe.close();
} catch (Throwable ex) {
}
}
}
public interface ScanListener {
void pressed(String key);
}
}
| 9,756 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
IsInstalled.java | /FileExtraction/Java_unseen/Morxander_IsInstalled/app/src/main/java/morxander/isinstalled/IsInstalled.java | package morxander.isinstalled;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import java.util.List;
/**
* Created by morxander on 3/21/17.
*/
public class IsInstalled {
public static boolean isIntalled(Context context, String packageName) {
boolean exist = false;
PackageManager pm = context.getPackageManager();
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> resolveInfoList = pm.queryIntentActivities(intent, 0);
for (ResolveInfo resolveInfo : resolveInfoList) {
if (resolveInfo.activityInfo.packageName.equals(packageName)) {
exist = true;
}
}
return exist;
}
}
| 854 | Java | .java | Morxander/IsInstalled | 39 | 9 | 0 | 2017-03-21T14:43:21Z | 2017-03-21T17:11:29Z |
AppsPackNames.java | /FileExtraction/Java_unseen/Morxander_IsInstalled/app/src/main/java/morxander/isinstalled/AppsPackNames.java | package morxander.isinstalled;
/**
* Created by morxander on 3/21/17.
*/
public class AppsPackNames {
public static final String FACEBOOK = "com.facebook.katana";
public static final String FACEBOOK_MESSENGER = "com.facebook.orca";
public static final String FACEBOOK_LITE = "com.facebook.lite";
public static final String FACEBOOK_MENTIONS = "com.facebook.Mentions";
public static final String FACEBOOK_GROUPS = "com.facebook.groups";
public static final String FACEBOOK_PAGES_MANAGER = "com.facebook.pages.app";
public static final String MSQRD = "me.msqrd.android";
public static final String WHATSAPP = "com.whatsapp";
public static final String VIBER = "com.viber.voip";
public static final String TELEGRAM = "org.telegram.messenger";
public static final String GOOGLE = "com.google.android.googlequicksearchbox";
public static final String CHROME = "com.android.chrome";
public static final String GOOGLE_DRIVE = "com.google.android.apps.docs";
public static final String GOOGLE_TRANSLATE = "com.google.android.apps.translate";
public static final String GOOGLE_CALENDAR = "com.google.android.calendar";
public static final String GMAIL = "com.google.android.gm";
public static final String YOUTUBE = "com.google.android.youtube";
public static final String GOOGLE_MAPS = "com.google.android.apps.maps";
public static final String GOOGLE_DOCS = "com.google.android.apps.docs.editors.docs";
public static final String GOOGLE_SHEETS = "com.google.android.apps.docs.editors.sheets";
public static final String HANGOUTS = "com.google.android.talk";
public static final String GOOGLE_ALLO = "com.google.android.apps.fireball";
public static final String CLEAN_MASTER = "com.cleanmaster.mguard";
public static final String UBER = "com.ubercab";
public static final String LYFT = "me.lyft.android";
public static final String DUBSMASH = "com.mobilemotion.dubsmash";
public static final String SNAPCHAT = "com.snapchat.android";
public static final String NETFLIX = "com.netflix.mediaclient";
public static final String QUORA = "com.quora.android";
public static final String LINKEDIN = "com.linkedin.android";
public static final String PINTEREST = "com.pinterest";
public static final String TUMBLR = "com.tumblr";
}
| 2,351 | Java | .java | Morxander/IsInstalled | 39 | 9 | 0 | 2017-03-21T14:43:21Z | 2017-03-21T17:11:29Z |
ExampleUnitTest.java | /FileExtraction/Java_unseen/ZeeRooo_MaterialFBook/app/src/test/java/me/zeeroooo/materialfb/ExampleUnitTest.java | package me.zeeroooo.materialfb;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
| 412 | Java | .java | ZeeRooo/MaterialFBook | 139 | 43 | 34 | 2016-09-12T22:22:02Z | 2021-07-18T16:20:04Z |
MFB.java | /FileExtraction/Java_unseen/ZeeRooo_MaterialFBook/app/src/main/java/me/zeeroooo/materialfb/MFB.java | package me.zeeroooo.materialfb;
import android.app.Application;
import android.content.Context;
import org.acra.ACRA;
import org.acra.annotation.ReportsCrashes;
/**
* Created by ZeeRooo on 15/04/18
*/
@ReportsCrashes(mailTo = "chavesjuan400@gmail.com")
public class MFB extends Application {
public static int colorPrimary, colorPrimaryDark, colorAccent, textColor;
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
ACRA.init(this);
}
}
| 517 | Java | .java | ZeeRooo/MaterialFBook | 139 | 43 | 34 | 2016-09-12T22:22:02Z | 2021-07-18T16:20:04Z |
MFBWebView.java | /FileExtraction/Java_unseen/ZeeRooo_MaterialFBook/app/src/main/java/me/zeeroooo/materialfb/webview/MFBWebView.java | package me.zeeroooo.materialfb.webview;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.webkit.WebView;
import androidx.core.view.NestedScrollingChild;
import androidx.core.view.NestedScrollingChildHelper;
import androidx.core.view.ViewCompat;
public class MFBWebView extends WebView implements NestedScrollingChild {
private final int[] mScrollOffset = new int[2];
private final int[] mScrollConsumed = new int[2];
private int mLastY;
private int mNestedOffsetY;
private NestedScrollingChildHelper mChildHelper;
private OnScrollChangedCallback mOnScrollChangedCallback;
public MFBWebView(Context context) {
super(context);
init();
}
public MFBWebView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MFBWebView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mChildHelper = new NestedScrollingChildHelper(this);
setNestedScrollingEnabled(true);
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
if (mOnScrollChangedCallback != null) {
mOnScrollChangedCallback.onScrollChange(this, l, t, oldl, oldt);
}
}
public void setOnScrollChangedCallback(final OnScrollChangedCallback mOnScrollChangedCallback) {
this.mOnScrollChangedCallback = mOnScrollChangedCallback;
}
@Override
public boolean isNestedScrollingEnabled() {
return mChildHelper.isNestedScrollingEnabled();
}
@Override
public void setNestedScrollingEnabled(boolean enabled) {
mChildHelper.setNestedScrollingEnabled(enabled);
}
@Override
public boolean startNestedScroll(int axes) {
return mChildHelper.startNestedScroll(axes);
}
@Override
public void stopNestedScroll() {
mChildHelper.stopNestedScroll();
}
@Override
public boolean hasNestedScrollingParent() {
return mChildHelper.hasNestedScrollingParent();
}
@Override
public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed,
int[] offsetInWindow) {
return mChildHelper.dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, offsetInWindow);
}
@Override
public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {
return mChildHelper.dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow);
}
@Override
public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
return mChildHelper.dispatchNestedFling(velocityX, velocityY, consumed);
}
@Override
public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
return mChildHelper.dispatchNestedPreFling(velocityX, velocityY);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
boolean rs = false;
final int action = event.getActionMasked();
if (action == MotionEvent.ACTION_DOWN) {
mNestedOffsetY = 0;
}
final int y = (int) event.getY();
event.offsetLocation(0, mNestedOffsetY);
switch (action) {
case MotionEvent.ACTION_DOWN:
rs = super.onTouchEvent(event);
mLastY = y;
break;
case MotionEvent.ACTION_MOVE:
int dy = mLastY - y;
final int oldY = getScrollY();
startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL);
if (dispatchNestedPreScroll(0, dy, mScrollConsumed, mScrollOffset)) {
dy -= mScrollConsumed[1];
event.offsetLocation(0, -mScrollOffset[1]);
mNestedOffsetY += mScrollOffset[1];
}
rs = super.onTouchEvent(event);
mLastY = y - mScrollOffset[1];
if (dy < 0) {
final int newScrollY = Math.max(0, oldY + dy);
dy -= newScrollY - oldY;
if (dispatchNestedScroll(0, newScrollY - dy, 0, dy, mScrollOffset)) {
event.offsetLocation(0, mScrollOffset[1]);
mNestedOffsetY += mScrollOffset[1];
mLastY -= mScrollOffset[1];
}
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
rs = super.onTouchEvent(event);
stopNestedScroll();
break;
}
return rs;
}
public interface OnScrollChangedCallback {
void onScrollChange(WebView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
}
} | 5,007 | Java | .java | ZeeRooo/MaterialFBook | 139 | 43 | 34 | 2016-09-12T22:22:02Z | 2021-07-18T16:20:04Z |
JavaScriptHelpers.java | /FileExtraction/Java_unseen/ZeeRooo_MaterialFBook/app/src/main/java/me/zeeroooo/materialfb/webview/JavaScriptHelpers.java | package me.zeeroooo.materialfb.webview;
import android.util.Base64;
import android.webkit.WebView;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
public class JavaScriptHelpers {
public static void updateNumsService(WebView view) {
view.loadUrl("javascript:(function(){function n_s(){android.getNums(document.querySelector(\"#notifications_jewel > a > div > div > span\").innerHTML,document.querySelector(\"#messages_jewel > a > div > div > span\").innerHTML,document.querySelector(\"#requests_jewel > a > div > div > span\").innerHTML,document.querySelector(\"#feed_jewel > a > div > div > span\").innerHTML),setTimeout(n_s,5000)}try{n_s()}catch(_){}})()");
}
// Thanks to Simple for Facebook. - https://github.com/creativetrendsapps/SimpleForFacebook/blob/master/app/src/main/java/com/creativetrends/simple/app/helpers/BadgeHelper.java#L36
public static void videoView(WebView view) {
view.loadUrl("javascript:(function prepareVideo() { var el = document.querySelectorAll('div[data-sigil]');for(var i=0;i<el.length; i++){var sigil = el[i].dataset.sigil;if(sigil.indexOf('inlineVideo') > -1){delete el[i].dataset.sigil;console.log(i);var jsonData = JSON.parse(el[i].dataset.store);el[i].setAttribute('onClick', 'Vid.LoadVideo(\"'+jsonData['src']+'\");');}}})()");
view.loadUrl("javascript:( window.onload=prepareVideo;)()");
}
public static void loadCSS(WebView view, String css) {
try {
final InputStream inputStream = new ByteArrayInputStream(css.getBytes(StandardCharsets.UTF_8));
final byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
inputStream.close();
view.loadUrl("javascript:(function() {var parent = document.getElementsByTagName('head').item(0);var style = document.createElement('style');style.type = 'text/css';style.innerHTML = window.atob('" + Base64.encodeToString(buffer, Base64.NO_WRAP) + "');parent.appendChild(style)})()");
} catch (Exception e) {
e.getStackTrace();
}
}
}
| 2,137 | Java | .java | ZeeRooo/MaterialFBook | 139 | 43 | 34 | 2016-09-12T22:22:02Z | 2021-07-18T16:20:04Z |
Helpers.java | /FileExtraction/Java_unseen/ZeeRooo_MaterialFBook/app/src/main/java/me/zeeroooo/materialfb/webview/Helpers.java | package me.zeeroooo.materialfb.webview;
import android.graphics.Color;
import android.view.Menu;
import android.webkit.CookieManager;
import me.zeeroooo.materialfb.MFB;
public class Helpers {
// Method to retrieve a single cookie
public static String getCookie() {
final CookieManager cookieManager = CookieManager.getInstance();
final String cookies = cookieManager.getCookie("https://m.facebook.com/");
if (cookies != null) {
final String[] temp = cookies.split(";");
for (String ar1 : temp) {
if (ar1.contains("c_user")) {
final String[] temp1 = ar1.split("=");
return temp1[1];
}
}
}
// Return null as we found no cookie
return null;
}
// Uncheck all items menu
public static void uncheckRadioMenu(Menu menu) {
for (int i = 0; i < menu.size(); i++) {
if (menu.getItem(i).isChecked()) {
menu.getItem(i).setChecked(false);
return;
}
}
}
static boolean isInteger(String str) {
return (str.matches("^-?\\d+$"));
}
// "clean" and decode an url, all in one
public static String cleanAndDecodeUrl(String url) {
return decodeUrl(cleanUrl(url));
}
// "clean" an url and remove Facebook tracking redirection
public static String cleanUrl(String url) {
return url.replace("http://lm.facebook.com/l.php?u=", "")
.replace("https://m.facebook.com/l.php?u=", "")
.replace("http://0.facebook.com/l.php?u=", "")
.replace("https://lm.facebook.com/l.php?u=", "")
.replaceAll("&h=.*", "")
.replaceAll("\\?acontext=.*", "")
.replace("&SharedWith=", "")
.replace("www.facebook.com", "m.facebook.com")
.replace("web.facebook.com", "m.facebook.com");
}
// url decoder, recreate all the special characters
private static String decodeUrl(String url) {
return url.replace("%3C", "<").replace("%3E", ">").replace("%23", "#").replace("%25", "%")
.replace("%7B", "{").replace("%7D", "}").replace("%7C", "|").replace("%5C", "\\")
.replace("%5E", "^").replace("%7E", "~").replace("%5B", "[").replace("%5D", "]")
.replace("%60", "`").replace("%3B", ";").replace("%2F", "/").replace("%3F", "?")
.replace("%3A", ":").replace("%40", "@").replace("%3D", "=").replace("%26", "&")
.replace("%24", "$").replace("%2B", "+").replace("%22", "\"").replace("%2C", ",")
.replace("%20", " ");
}
public static String decodeImg(String img_url) {
return img_url.replace("\\3a ", ":").replace("efg\\3d ", "oh=").replace("\\3d ", "=").replace("\\26 ", "&").replace("\\", "").replace("&", "&");
}
public static String cssThemeEngine(byte themeMode) {
final StringBuilder stringBuilder = new StringBuilder();
int sensitiveColor;
if (themeMode == 1) // if we are using a dark mode + dark accent color, some texts will be black on black, so let's manage this exception
sensitiveColor = Color.WHITE;
else
sensitiveColor = MFB.colorPrimary;
stringBuilder.append("._4e81, ._4kk6, .blueName, ._2a_i._2a_i a, ._5pxa ._5pxc a, .fcb, ._67i4 ._5jjz ._5c9u, ._vqv .read, ._vqv, ._3bg5 ._52x2, ._6x2x, ._6xqt, .touch ._5lm6, ._1e8b, ._52jb, #u_0_d, #u_0_4l, #u_0_36 { color: #").append(Integer.toHexString(sensitiveColor).substring(2)).append(" !important; }.touch ._x0b { border-bottom: 2px solid #").append(Integer.toHexString(MFB.colorPrimaryDark).substring(2)).append("; color: #").append(Integer.toHexString(MFB.colorPrimaryDark).substring(2)).append("; }.touch ._4_d0 ._4_d1 ._55cx, ._u42 ._55fj, ._6j_d { background: #").append(Integer.toHexString(MFB.colorPrimary).substring(2)).append(" !important;text-shadow: 0 0px; }._7gxn ._59tg, ._8hp4, ._26vk._56bu, .touch ._26vk._56bv, ._36bl ._2x1r, ._36bl ._2thz { background-color: #").append(Integer.toHexString(MFB.colorPrimary).substring(2)).append(" !important; } ._52z5._7gxn { height: 89px; border-bottom: 0px; border-top: 0px; background: #").append(Integer.toHexString(MFB.colorPrimary).substring(2)).append("; }._129- { border-top: 0px; }._7izv ._7i-0 { border-bottom: 1px solid #").append(Integer.toHexString(MFB.colorAccent).substring(2)).append("; }._15kl._15kl ._77li, ._15kj._15kj a, .touch a.sub, ._2eo-._4b44, .touch ._78xz, .touch ._5qc4._5qc4 a, .touch ._5qc4._5qc4._5qc4 a, ._4gux, ._6dsj ._3gin, ._7izv ._7iz_, ._52j9, ._4_d0 ._4_d1, .fcl, .fcg, ._x0a, ._86nv, ._20u1, .touch .mfsm, ._52ja, ._7-1j, ._5tg_, ._5qc3._5qc3 a, ._7msl { color: #").append(Integer.toHexString(MFB.colorAccent).substring(2)).append(" !important; }.aclb, ._67iu, ._2ykg .unreadMessage, ._2b06 { background-color: #").append(Integer.toHexString(MFB.colorPrimary).substring(2)).append("40 !important; }._86nt._8n4c, ._7cui { background-color: #").append(Integer.toHexString(MFB.colorPrimaryDark).substring(2)).append("40; color: #").append(Integer.toHexString(MFB.colorPrimaryDark).substring(2)).append("}._34em ._34ee { background-color: #").append(Integer.toHexString(MFB.colorPrimary).substring(2)).append(" !important; color: #fff; }._34ee { background-color: transparent !important; border: 1px solid #").append(Integer.toHexString(MFB.colorPrimary).substring(2)).append("; } .touch .btn.iconOnly, .touch .btnC, .touch .btnI.bgb { background: #").append(Integer.toHexString(MFB.colorPrimaryDark).substring(2)).append("; border: 0px; }.acw { border: 0; }.touch ._5c9u, .touch ._5ca9, .touch button._5c9u { text-shadow: 0 0px; }._u42 ._5i9c { border-radius: 50%; }._1e8h { border-top: 0px; }.ib .l { border-radius: 50%; }");
if (themeMode == 1 || themeMode == 2)
stringBuilder.append("._55wo, ._2am8, ._vi6 ._42rg, ._7gxp, ._67i4 ._67iv #messages_search_box .quicksearch, .touch ._1oby ._5c9u, ._10c_, ._77xj, ._6vzz, #timelineBody, ._3-8x, ._3f50>._5rgr, ._45kb>div, ._5-lw, ._13fn, ._hdn._hdn, #u_0_35, #u_0_4k, #u_1_1i, #u_1_0, #u_0_4m, #u_0_5i, #u_0_44, #u_0_37, .touch ._6-l .composerInput, ._13-f, form { background: #1e1e1e !important; }._2v9s, #root, ._59e9, ._vqv, .touch ._4_d0, ._3ioy._3ioy ._uww, ._403n, ._13e_, .groupChromeView.feedRevamp, ._4_xl, ._-j8, ._-j9, ._6o5v, #u_0_2, ._484w, ._-j7, .acw, ._21db { background: #121212 !important; }._6beq, ._5pz4, ._5lp4, ._5lp5, .touch ._1f9d, .touch ._3tap, ._36dc { background: #1e1e1e !important; border-bottom: 0px; border-top: 0px; }._44qk { border-bottom: 0px; }._34ee, textarea, input, ._u42 ._52x7, ._5rgt p, ._5t8z p, .ib .c, ._52jc, .touch ._5b6o ._5b6q, ._21dc, ._2b06, ._5g68, ._43lx._43lx a { color: #aaaaaa !important; }.touch ._52t1, ._uww, ._5-lx, .touch ._26vk._56bt[disabled] { border: 1px solid #1e1e1e !important; background: #121212; }._3bg5 ._52x6 { border-top-color: #2b324600 !important; background: #1e1e1e !important; }._3bg5 ._52x1, ._z-w { background: #121212 !important; border-bottom: 0px; border-top: 0px; }._4gus, ._67i4 ._67iu ._3z10, h1, h2, h3, h4, h5, h6, ._52jj, ._njv, ._5c4t ._1g06 { color: white; } .touch ._55so._59f6::before, .touch.wp.x1-5 ._55so._59f6::before, .touch.wp.x2 ._55so._59f6::before, .touch ._59f6 ._55st ._5c9u { background: #1e1e1e !important; text-shadow: 0 0px; } ._a58 _9_7 _2rgt _1j-f _2rgt { background-color: #121212 !important; }"); // ._7om2, lele
if (themeMode == 1 || themeMode == 3)
stringBuilder.append("._34em ._34ee, .touch ._8hq8, ._6j_d ._6j_c, ._59tg, ._u42 ._55fj { color: #").append(Integer.toHexString(MFB.colorAccent).substring(2)).append(" !important; }");
// stringBuilder.append("._5rgr, ._5rgt p { -webkit-user-select: initial !important; }");
return stringBuilder.toString();
}
}
| 8,008 | Java | .java | ZeeRooo/MaterialFBook | 139 | 43 | 34 | 2016-09-12T22:22:02Z | 2021-07-18T16:20:04Z |
JavaScriptInterfaces.java | /FileExtraction/Java_unseen/ZeeRooo_MaterialFBook/app/src/main/java/me/zeeroooo/materialfb/webview/JavaScriptInterfaces.java | package me.zeeroooo.materialfb.webview;
import android.content.SharedPreferences;
import android.webkit.JavascriptInterface;
import androidx.preference.PreferenceManager;
import me.zeeroooo.materialfb.activities.MainActivity;
@SuppressWarnings("unused")
public class JavaScriptInterfaces {
private final MainActivity mContext;
private final SharedPreferences mPreferences;
// Instantiate the interface and set the context
public JavaScriptInterfaces(MainActivity c) {
mContext = c;
mPreferences = PreferenceManager.getDefaultSharedPreferences(c);
}
@JavascriptInterface
public void getNums(final String notifications, final String messages, final String requests, final String feed) {
final int notifications_int = Helpers.isInteger(notifications) ? Integer.parseInt(notifications) : 0;
final int messages_int = Helpers.isInteger(messages) ? Integer.parseInt(messages) : 0;
final int requests_int = Helpers.isInteger(requests) ? Integer.parseInt(requests) : 0;
final int mr_int = Helpers.isInteger(feed) ? Integer.parseInt(feed) : 0;
mContext.runOnUiThread(new Runnable() {
@Override
public void run() {
mContext.setNotificationNum(notifications_int);
mContext.setMessagesNum(messages_int);
mContext.setRequestsNum(requests_int);
mContext.setMrNum(mr_int);
}
});
}
}
| 1,469 | Java | .java | ZeeRooo/MaterialFBook | 139 | 43 | 34 | 2016-09-12T22:22:02Z | 2021-07-18T16:20:04Z |
SettingsActivity.java | /FileExtraction/Java_unseen/ZeeRooo_MaterialFBook/app/src/main/java/me/zeeroooo/materialfb/activities/SettingsActivity.java | /*
* Code taken from:
* - FaceSlim by indywidualny. Thanks.
* - Toffed by JakeLane. Thanks.
*/
package me.zeeroooo.materialfb.activities;
import android.content.Intent;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.appcompat.widget.Toolbar;
import me.zeeroooo.materialfb.MFB;
import me.zeeroooo.materialfb.R;
import me.zeeroooo.materialfb.fragments.SettingsFragment;
public class SettingsActivity extends MFBActivity {
@Override
protected void create(Bundle savedInstanceState) {
super.create(savedInstanceState);
setContentView(R.layout.activity_settings);
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new SettingsFragment()).commit();
findViewById(R.id.settings_root_view).setBackgroundColor(MFB.colorPrimary);
final Toolbar mToolbar = findViewById(R.id.settings_toolbar);
mToolbar.setTitle(getString(R.string.settings));
mToolbar.setNavigationIcon(R.mipmap.ic_launcher);
final Drawable backArrowDrawable = getResources().getDrawable(R.drawable.abc_ic_ab_back_material);
mToolbar.setTitleTextColor(MFB.textColor);
backArrowDrawable.setColorFilter(MFB.textColor, PorterDuff.Mode.SRC_ATOP);
setSupportActionBar(mToolbar);
getSupportActionBar().setHomeAsUpIndicator(backArrowDrawable);
}
@Override
public void onBackPressed() {
startActivity(new Intent(this, MainActivity.class).putExtra("apply", true));
super.onBackPressed();
}
} | 1,590 | Java | .java | ZeeRooo/MaterialFBook | 139 | 43 | 34 | 2016-09-12T22:22:02Z | 2021-07-18T16:20:04Z |
MainActivity.java | /FileExtraction/Java_unseen/ZeeRooo_MaterialFBook/app/src/main/java/me/zeeroooo/materialfb/activities/MainActivity.java | //
//* Code taken from:
//* - FaceSlim by indywidualny. Thanks.
//* - Folio for Facebook by creativetrendsapps. Thanks.
//* - Toffed by JakeLane. Thanks.
//
package me.zeeroooo.materialfb.activities;
import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.net.Uri;
import android.net.UrlQuerySanitizer;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.URLUtil;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.graphics.BlendModeColorFilterCompat;
import androidx.core.graphics.BlendModeCompat;
import androidx.core.view.GravityCompat;
import androidx.core.view.ViewCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import org.jsoup.Jsoup;
import org.jsoup.select.Elements;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import me.zeeroooo.materialfb.MFB;
import me.zeeroooo.materialfb.R;
import me.zeeroooo.materialfb.adapters.AdapterBookmarks;
import me.zeeroooo.materialfb.misc.DatabaseHelper;
import me.zeeroooo.materialfb.misc.ModelBookmarks;
import me.zeeroooo.materialfb.misc.UserInfo;
import me.zeeroooo.materialfb.notifications.NotificationsService;
import me.zeeroooo.materialfb.ui.CookingAToast;
import me.zeeroooo.materialfb.ui.MFBFloatingActionButton;
import me.zeeroooo.materialfb.ui.MFBResources;
import me.zeeroooo.materialfb.webview.Helpers;
import me.zeeroooo.materialfb.webview.JavaScriptHelpers;
import me.zeeroooo.materialfb.webview.JavaScriptInterfaces;
import me.zeeroooo.materialfb.webview.MFBWebView;
public class MainActivity extends MFBActivity implements NavigationView.OnNavigationItemSelectedListener, Handler.Callback {
private ValueCallback<Uri[]> mFilePathCallback;
private Uri mCapturedImageURI = null, sharedFromGallery;
private ValueCallback<Uri> mUploadMessage;
private int lastEvent, screenHeight;
private boolean showAnimation, showHeader = false, loadCss = true, hideHeaderPref;
private String baseURL, mCameraPhotoPath, Url;
private SwipeRefreshLayout swipeView;
private NavigationView mNavigationView;
private MFBFloatingActionButton mfbFloatingActionButton;
private MFBWebView mWebView;
private DatabaseHelper DBHelper;
private AdapterBookmarks BLAdapter;
private ListView BookmarksListView;
private ArrayList<ModelBookmarks> bookmarks;
private ModelBookmarks bk;
private DrawerLayout drawer;
private Elements elements;
private Toolbar searchToolbar;
private MenuItem searchItem;
private SearchView searchView;
private Handler badgeUpdate;
private Runnable badgeTask;
private TextView mr_badge, fr_badge, notif_badge, msg_badge;
private Cursor cursor;
private View circleRevealView;
private final StringBuilder css = new StringBuilder();
private final Handler mHandler = new Handler(this);
@Override
protected void create(Bundle savedInstanceState) {
super.create(savedInstanceState);
WorkManager.getInstance().enqueue(new OneTimeWorkRequest.Builder(NotificationsService.class).build());
((MFBResources) getResources()).setColors(sharedPreferences);
setContentView(R.layout.activity_main);
final AppBarLayout appBarLayout = findViewById(R.id.appbarlayout);
appBarLayout.setBackgroundColor(MFB.colorPrimary);
final CoordinatorLayout coordinatorLayoutRootView = findViewById(R.id.app_bar_main_root_view);
coordinatorLayoutRootView.setBackgroundColor(MFB.colorPrimary);
final CoordinatorLayout coordinatorLayout = findViewById(R.id.app_bar_main_coordinator_layout);
ViewCompat.setOnApplyWindowInsetsListener(coordinatorLayout, (view, insets) ->
ViewCompat.onApplyWindowInsets(coordinatorLayout, insets.replaceSystemWindowInsets(insets.getSystemWindowInsetLeft(), 0, insets.getSystemWindowInsetRight(), insets.getSystemWindowInsetBottom()))
);
mWebView = findViewById(R.id.webview);
mNavigationView = findViewById(R.id.nav_view);
drawer = findViewById(R.id.drawer_layout);
final Toolbar mToolbar = findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
// Setup the DrawLayout
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
if (themeMode == 0 | themeMode == 1) {
toggle.getDrawerArrowDrawable().setColor(Color.WHITE);
mToolbar.setTitleTextColor(Color.WHITE);
} else if (themeMode == 2) {
toggle.getDrawerArrowDrawable().setColor(Color.BLACK);
mToolbar.setTitleTextColor(Color.BLACK);
}
MFB.textColor = toggle.getDrawerArrowDrawable().getColor();
drawer.addDrawerListener(toggle);
toggle.syncState();
URLs();
switch (sharedPreferences.getString("start_url", "Most_recent")) {
case "Most_recent":
baseURL += "home.php?sk=h_chr";
break;
case "Top_stories":
baseURL += "home.php?sk=h_nor";
break;
case "Messages":
baseURL += "messages/";
break;
default:
break;
}
UrlIntent(getIntent());
swipeView = findViewById(R.id.swipeLayout);
if (themeMode == 0 | themeMode == 1)
swipeView.setColorSchemeResources(android.R.color.white);
else
swipeView.setColorSchemeResources(android.R.color.black);
swipeView.setProgressBackgroundColorSchemeColor(getResources().getColor(R.color.colorPrimary));
swipeView.setOnRefreshListener(() -> mWebView.reload());
final Rect rect = new Rect();
coordinatorLayoutRootView.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
coordinatorLayoutRootView.getWindowVisibleDisplayFrame(rect);
screenHeight = coordinatorLayoutRootView.getHeight();
swipeView.setEnabled((screenHeight - rect.bottom) < screenHeight * 0.15);
});
// Inflate the FAB menu
mfbFloatingActionButton = findViewById(R.id.menuFAB);
View.OnClickListener mFABClickListener = (View v) -> {
switch (v.getId()) {
case 1:
mWebView.loadUrl("javascript:(function(){document.getElementsByClassName('_3-99')[1].click()})()");
swipeView.setEnabled(false);
break;
case 2:
mWebView.loadUrl("javascript:(function(){document.getElementsByClassName('_3-99')[0].click()})()");
swipeView.setEnabled(false);
break;
case 3:
mWebView.loadUrl("javascript:(function(){document.getElementsByClassName('_3-99')[3].click()})()");
swipeView.setEnabled(false);
break;
case 4:
mWebView.scrollTo(0, 0);
break;
case 5:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, mWebView.getUrl());
startActivity(Intent.createChooser(shareIntent, getString(R.string.context_share_link)));
break;
}
};
mfbFloatingActionButton.addButton(getResources().getDrawable(R.drawable.ic_fab_checkin), getString(R.string.fab_checkin), FloatingActionButton.SIZE_MINI, mFABClickListener);
mfbFloatingActionButton.addButton(getResources().getDrawable(R.drawable.ic_fab_photo), getString(R.string.fab_photo), FloatingActionButton.SIZE_MINI, mFABClickListener);
mfbFloatingActionButton.addButton(getResources().getDrawable(R.drawable.ic_fab_text), getString(R.string.fab_text), FloatingActionButton.SIZE_MINI, mFABClickListener);
mfbFloatingActionButton.addButton(getResources().getDrawable(R.drawable.ic_fab_jump_top), getString(R.string.fab_jump_top), FloatingActionButton.SIZE_MINI, mFABClickListener);
mfbFloatingActionButton.addButton(getResources().getDrawable(R.drawable.ic_share), getString(R.string.context_share_link), FloatingActionButton.SIZE_MINI, mFABClickListener);
}
@Override
protected void onPostCreate(@Nullable Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
searchToolbar();
final int defaultColor = mNavigationView.getItemTextColor().getDefaultColor();
ColorStateList colorStateList = new ColorStateList(
new int[][]{new int[]{android.R.attr.state_checked}, new int[]{android.R.attr.state_enabled}, new int[]{android.R.attr.state_pressed}, new int[]{android.R.attr.state_focused}, new int[]{android.R.attr.state_pressed}},
new int[]{MFB.colorPrimary, defaultColor, defaultColor, defaultColor, defaultColor}
);
mNavigationView.setItemTextColor(colorStateList);
mNavigationView.setItemIconTintList(colorStateList);
mNavigationView.setNavigationItemSelectedListener(this);
mNavigationView.setCheckedItem(R.id.nav_most_recent);
DBHelper = new DatabaseHelper(this);
bookmarks = new ArrayList<>();
cursor = DBHelper.getReadableDatabase().rawQuery("SELECT TITLE, URL FROM mfb_table", null);
while (cursor.moveToNext()) {
if (cursor.getString(0) != null && cursor.getString(1) != null) {
bk = new ModelBookmarks(cursor.getString(0), cursor.getString(1));
bookmarks.add(bk);
}
}
BLAdapter = new AdapterBookmarks(this, bookmarks, DBHelper);
BookmarksListView = findViewById(R.id.bookmarksListView);
BookmarksListView.setAdapter(BLAdapter);
BookmarksListView.setOnItemClickListener((adapter, view, position, arg) -> {
mWebView.loadUrl(((ModelBookmarks) BookmarksListView.getAdapter().getItem(position)).getUrl());
drawer.closeDrawers();
});
final MaterialButton newbookmark = findViewById(R.id.add_bookmark);
newbookmark.setBackgroundColor(MFB.colorPrimary);
newbookmark.setTextColor(MFB.textColor);
newbookmark.getCompoundDrawablesRelative()[2].setColorFilter(BlendModeColorFilterCompat.createBlendModeColorFilterCompat(MFB.textColor, BlendModeCompat.SRC_ATOP));
newbookmark.setOnClickListener((View v) -> {
bk = new ModelBookmarks(mWebView.getTitle(), mWebView.getUrl());
DBHelper.addData(bk.getTitle(), bk.getUrl(), null);
bookmarks.add(bk);
BLAdapter.notifyDataSetChanged();
CookingAToast.cooking(MainActivity.this, getString(R.string.new_bookmark) + " " + mWebView.getTitle(), Color.WHITE, Color.parseColor("#214594"), R.drawable.ic_bookmarks, false).show();
});
mr_badge = (TextView) mNavigationView.getMenu().findItem(R.id.nav_most_recent).getActionView();
fr_badge = (TextView) mNavigationView.getMenu().findItem(R.id.nav_friendreq).getActionView();
// Hide buttons if they are disabled
mNavigationView.getMenu().findItem(R.id.nav_groups).setVisible(sharedPreferences.getBoolean("nav_groups", true));
mNavigationView.getMenu().findItem(R.id.nav_search).setVisible(sharedPreferences.getBoolean("nav_search", true));
mNavigationView.getMenu().findItem(R.id.nav_mainmenu).setVisible(sharedPreferences.getBoolean("nav_mainmenu", true));
mNavigationView.getMenu().findItem(R.id.nav_most_recent).setVisible(sharedPreferences.getBoolean("nav_most_recent", true));
mNavigationView.getMenu().findItem(R.id.nav_events).setVisible(sharedPreferences.getBoolean("nav_events", true));
mNavigationView.getMenu().findItem(R.id.nav_photos).setVisible(sharedPreferences.getBoolean("nav_photos", true));
mNavigationView.getMenu().findItem(R.id.nav_top_stories).setVisible(sharedPreferences.getBoolean("nav_top_stories", true));
mNavigationView.getMenu().findItem(R.id.nav_friendreq).setVisible(sharedPreferences.getBoolean("nav_friendreq", true));
mWebView.setOnScrollChangedCallback((WebView view, int scrollX, int scrollY, int oldScrollX, int oldScrollY) -> {
// Make sure the hiding is enabled and the scroll was significant
if (Math.abs(oldScrollY - scrollY) > 4) {
if (scrollY > oldScrollY) {
// User scrolled down, hide the button
mfbFloatingActionButton.hide();
} else if (scrollY < oldScrollY) {
// User scrolled up, show the button
mfbFloatingActionButton.show();
}
}
});
hideHeaderPref = sharedPreferences.getBoolean("hide_menu_bar", true);
mWebView.getSettings().setGeolocationEnabled(sharedPreferences.getBoolean("location_enabled", false));
mWebView.getSettings().setMinimumFontSize(Integer.parseInt(sharedPreferences.getString("textScale", "1")));
mWebView.addJavascriptInterface(new JavaScriptInterfaces(this), "android");
mWebView.addJavascriptInterface(this, "Vid");
mWebView.getSettings().setBlockNetworkImage(sharedPreferences.getBoolean("stop_images", false));
mWebView.getSettings().setAppCacheEnabled(true);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setAllowFileAccess(true);
mWebView.getSettings().setAllowContentAccess(true);
mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
if (Build.VERSION.SDK_INT >= 19)
mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
else
mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
mWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
mWebView.getSettings().setUserAgentString("Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36");
mWebView.setWebViewClient(new WebViewClient() {
@SuppressLint("NewApi")
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return shouldOverrideUrlLoading(view, request.getUrl().toString());
}
@SuppressWarnings("deprecation")
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// clean an url from facebook redirection before processing (no more blank pages on back)
url = Helpers.cleanAndDecodeUrl(url);
if (url.contains("mailto:"))
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
if (Uri.parse(url).getHost().endsWith("facebook.com")
|| Uri.parse(url).getHost().endsWith("*.facebook.com")
|| Uri.parse(url).getHost().endsWith("akamaihd.net")
|| Uri.parse(url).getHost().endsWith("ad.doubleclick.net")
|| Uri.parse(url).getHost().endsWith("sync.liverail.com")
|| Uri.parse(url).getHost().endsWith("cdn.fbsbx.com")
|| Uri.parse(url).getHost().endsWith("lookaside.fbsbx.com")) {
return false;
}
if (url.contains("giphy") || url.contains("gifspace") || url.contains("tumblr") || url.contains("gph.is") || url.contains("gif") || url.contains("fbcdn.net") || url.contains("imgur")) {
if (url.contains("giphy") || url.contains("gph")) {
if (!url.endsWith(".gif")) {
if (url.contains("giphy.com") || url.contains("html5"))
url = String.format("https://media.giphy.com/media/%s/giphy.gif", url.replace("http://giphy.com/gifs/", ""));
else if (url.contains("gph.is") && !url.contains("html5")) {
view.loadUrl(url);
url = String.format("https://media.giphy.com/media/%s/giphy.gif", url.replace("http://giphy.com/gifs/", ""));
}
if (url.contains("media.giphy.com/media/") && !url.contains("html5")) {
String[] giphy = url.split("-");
String giphy_id = giphy[giphy.length - 1];
url = "https://media.giphy.com/media/" + giphy_id;
}
if (url.contains("media.giphy.com/media/http://media")) {
String[] gph = url.split("/");
String gph_id = gph[gph.length - 2];
url = "https://media.giphy.com/media/" + gph_id + "/giphy.gif";
}
if (url.contains("html5/giphy.gif")) {
String[] giphy_html5 = url.split("/");
String giphy_html5_id = giphy_html5[giphy_html5.length - 3];
url = "https://media.giphy.com/media/" + giphy_html5_id + "/giphy.gif";
}
}
if (url.contains("?")) {
String[] giphy1 = url.split("\\?");
String giphy_html5_id = giphy1[0];
url = giphy_html5_id + "/giphy.gif";
}
}
if (url.contains("imgur")) {
if (!url.endsWith(".gif") && !url.endsWith(".jpg")) {
getSrc(url, "div.post-image", "img");
url = "https:" + elements.attr("src");
}
}
if (url.contains("media.upgifs.com")) {
if (!url.endsWith(".gif")) {
getSrc(url, "div.gif-pager-container", "img#main-gif");
url = elements.attr("src");
}
}
imageLoader(url);
return true;
} else {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}
}
private void getSrc(final String url, final String select, final String select2) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void[] params) {
try {
elements = Jsoup.connect(url).get().select(select).select(select2);
} catch (IOException ioex) {
ioex.getStackTrace();
}
return null;
}
}.execute();
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
swipeView.setRefreshing(true);
if (url.contains("https://mbasic.facebook.com/home.php?s="))
view.loadUrl(baseURL);
}
@Override
public void onLoadResource(WebView view, String url) {
JavaScriptHelpers.videoView(view);
if (url.contains("facebook.com/composer/mbasic/") || url.contains("https://m.facebook.com/sharer.php?sid="))
showHeader = true;
if (loadCss) {
if (showHeader || !hideHeaderPref) {
css.append("#header { display: inherit; }");
} else
css.append("#header { display: none; }");
css.append(Helpers.cssThemeEngine(themeMode));
// Hide the status editor on the News Feed if setting is enabled
if (sharedPreferences.getBoolean("hide_editor_newsfeed", true))
css.append("#MComposer { display:none }");
// Hide 'Sponsored' content (ads)
if (sharedPreferences.getBoolean("hide_sponsored", true))
css.append("article[data-ft*=ei] { display:none }");
// Hide birthday content from News Feed
if (sharedPreferences.getBoolean("hide_birthdays", true))
css.append("article#u_1j_4 { display:none } article._55wm._5e4e._5fjt { display:none }");
if (sharedPreferences.getBoolean("comments_recently", true))
css.append("._5gh8 ._15ks:last-child, ._5gh8 ._15ks+._4u3j { display:none }");
// css.append("article#u_0_q._d2r{display:none}* { -webkit-tap-highlight-color:transparent; outline:0 }");
css.append("._i81:after { display: none; }");
JavaScriptHelpers.loadCSS(view, css.toString());
loadCss = false;
}
if (url.contains("/photo/view_full_size/?fbid="))
imageLoader(url.split("&ref_component")[0]);
}
@Override
public void onPageFinished(WebView view, String url) {
swipeView.setRefreshing(false);
css.delete(0, css.length());
if (url.contains("lookaside") || url.contains("cdn.fbsbx.com")) {
Url = url;
RequestStoragePermission();
}
// Enable or disable FAB
if (url.contains("messages") || !sharedPreferences.getBoolean("fab_enable", false))
mfbFloatingActionButton.setVisibility(View.GONE);
else
mfbFloatingActionButton.setVisibility(View.VISIBLE);
if (url.contains("https://mbasic.facebook.com/composer/?text=")) {
final UrlQuerySanitizer sanitizer = new UrlQuerySanitizer();
sanitizer.setAllowUnregisteredParamaters(true);
sanitizer.parseUrl(url);
final String param = sanitizer.getValue("text");
view.loadUrl("javascript:(function(){document.querySelector('#composerInput').innerHTML='" + param + "'})()");
}
if (url.contains("https://m.facebook.com/public/")) {
final String[] user = url.split("/");
final String profile = user[user.length - 1];
view.loadUrl("javascript:(function(){document.querySelector('input#u_0_0._5whq.input').value='" + profile + "'})()");
view.loadUrl("javascript:(function(){try{document.querySelector('button#u_0_1.btn.btnD.mfss.touchable').disabled = false}catch(_){}})()");
view.loadUrl("javascript:(function(){try{document.querySelector('button#u_0_1.btn.btnD.mfss.touchable').click()}catch(_){}})()");
}
if (sharedFromGallery != null)
view.loadUrl("javascript:(function(){try{document.getElementsByName('view_photo')[0].click()}catch(_){document.getElementsByClassName('bb bc')[0].click()}})()");
if (showHeader)
showHeader = false;
loadCss = true;
}
});
mWebView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int progress) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && showAnimation && progress == 100) {
circleReveal();
showAnimation = false;
}
}
@Override
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
// Double check that we don't have any existing callbacks
if (sharedFromGallery != null)
filePathCallback.onReceiveValue(new Uri[]{sharedFromGallery});
mFilePathCallback = filePathCallback;
// Set up the take picture intent
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
} else
takePictureIntent = null;
}
// Set up the intent to get an existing image
final Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("*/*");
// Set up the intents for the Intent chooser
Intent[] intentArray;
if (takePictureIntent != null)
intentArray = new Intent[]{takePictureIntent};
else
intentArray = new Intent[0];
if (sharedFromGallery == null) {
final Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, 1);
}
return true;
}
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
openFileChooser(uploadMsg, acceptType);
}
// openFileChooser for Android 3.0+
private void openFileChooser(ValueCallback uploadMsg, String acceptType) {
// Update message
if (sharedFromGallery != null)
uploadMsg.onReceiveValue(sharedFromGallery);
else
mUploadMessage = uploadMsg;
final File imageStorageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
if (!imageStorageDir.exists())
imageStorageDir.mkdirs();
// Create camera captured image file path and name
final File file = new File(imageStorageDir + File.separator + "IMG_" + System.currentTimeMillis() + ".jpg");
mCapturedImageURI = Uri.fromFile(file);
// Camera capture image intent
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
final Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
if (sharedFromGallery == null) {
final Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{captureIntent});
startActivityForResult(chooserIntent, 2888);
}
}
private File createImageFile() throws IOException {
// Create an image file name
final File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return File.createTempFile("IMG_" + System.currentTimeMillis(), ".jpg", storageDir);
}
public void onGeolocationPermissionsShowPrompt(final String origin, final GeolocationPermissions.Callback callback) {
callback.invoke(origin, true, false);
}
@Override
public void onReceivedTitle(WebView view, String title) {
if (view.getUrl().contains("home.php?sk=h_nor"))
setTitle(R.string.menu_top_stories);
else if (title.contains("Facebook"))
setTitle(R.string.menu_most_recent);
else
setTitle(title);
}
});
mWebView.setOnTouchListener((View v, MotionEvent event) -> {
if (event.getAction() == MotionEvent.ACTION_UP && lastEvent == MotionEvent.ACTION_DOWN && mWebView.getHitTestResult().getType() == 5) {
mWebView.requestFocusNodeHref(mHandler.obtainMessage());
mHandler.sendMessage(mHandler.obtainMessage());
}
lastEvent = event.getAction();
return v.performClick();
});
}
@Override
public boolean handleMessage(Message msg) {
imageLoader(msg.getData().getString("src"));
return true;
}
private void imageLoader(String url) {
startActivity(new Intent(this, PhotoActivity.class).putExtra("link", url).putExtra("title", mWebView.getTitle()));
}
public void RequestStoragePermission() {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
private void URLs() {
if (!sharedPreferences.getBoolean("save_data", false))
baseURL = "https://m.facebook.com/";
else
baseURL = "https://mbasic.facebook.com/";
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
final DownloadManager.Request request = new DownloadManager.Request(Uri.parse(Url));
final File destinationFile = new File(Environment.DIRECTORY_DOWNLOADS, Uri.parse(Url).getLastPathSegment());
request.setDestinationUri(Uri.fromFile(destinationFile));
request.setVisibleInDownloadsUi(true);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
((DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE)).enqueue(request);
mWebView.goBack();
CookingAToast.cooking(this, getString(R.string.downloaded), Color.WHITE, Color.parseColor("#00C851"), R.drawable.ic_download, false).show();
} else
CookingAToast.cooking(this, getString(R.string.permission_denied), Color.WHITE, Color.parseColor("#ff4444"), R.drawable.ic_error, true).show();
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
if (intent.getBooleanExtra("apply", false))
recreate();
URLs();
UrlIntent(intent);
}
@Override
protected void onResume() {
super.onResume();
new UserInfo().execute(this);
URLs();
mWebView.onResume();
mWebView.resumeTimers();
if (Helpers.getCookie() != null && !sharedPreferences.getBoolean("save_data", false)) {
badgeUpdate = new Handler();
badgeTask = () -> {
JavaScriptHelpers.updateNumsService(mWebView);
badgeUpdate.postDelayed(badgeTask, 15000);
};
badgeTask.run();
}
}
@Override
protected void onPause() {
super.onPause();
mWebView.onPause();
if (badgeTask != null && badgeUpdate != null)
badgeUpdate.removeCallbacks(badgeTask);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (!cursor.isClosed()) {
DBHelper.close();
cursor.close();
}
mWebView.clearCache(true);
mWebView.clearHistory();
mWebView.removeAllViews();
mWebView.destroy();
if (badgeTask != null && badgeUpdate != null)
badgeUpdate.removeCallbacks(badgeTask);
}
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
// Thanks to Koras for the tutorial. http://dev.indywidualni.org/2015/02/an-advanced-webview-with-some-cool-features
super.onActivityResult(requestCode, resultCode, data);
if (Build.VERSION.SDK_INT >= 21) {
if (requestCode != 1 || mFilePathCallback == null)
return;
Uri[] results = null;
// Check that the response is a good one
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
// If there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else {
final String dataString = data.getDataString();
if (dataString != null)
results = new Uri[]{Uri.parse(dataString)};
}
}
mFilePathCallback.onReceiveValue(results);
mFilePathCallback = null;
} else {
if (requestCode == 2888) {
if (null == this.mUploadMessage)
return;
Uri result;
if (resultCode != RESULT_OK)
result = null;
else {
// retrieve from the private variable if the intent is null
result = data == null ? mCapturedImageURI : data.getData();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
}
private Point getPointOfView(View view) {
final int[] location = new int[2];
view.getLocationInWindow(location);
return new Point(location[0], location[1]);
}
@SuppressWarnings("NewApi")
private void circleReveal() {
final int radius = (int) Math.hypot(mWebView.getWidth(), mWebView.getHeight());
int x, y;
if (circleRevealView != null) {
Point point = getPointOfView(circleRevealView);
x = point.x;
y = point.y;
} else {
x = 0;
y = mWebView.getHeight() / 2;
}
final Animator anim = ViewAnimationUtils.createCircularReveal(mWebView, x, y, 0, radius);
anim.setDuration(300);
anim.start();
mWebView.setVisibility(View.VISIBLE);
}
@Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START))
drawer.closeDrawers();
if (searchToolbar.hasExpandedActionView())
searchItem.collapseActionView();
else if (mWebView.canGoBack())
mWebView.goBack();
else
super.onBackPressed();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
final View action_notif = menu.findItem(R.id.action_notifications).getActionView();
final View action_msg = menu.findItem(R.id.action_messages).getActionView();
notif_badge = action_notif.findViewById(R.id.badge_count);
msg_badge = action_msg.findViewById(R.id.badge_count);
final ImageView notif = action_notif.findViewById(R.id.badge_icon);
setBackground(notif);
notif.setImageDrawable(getResources().getDrawable(R.drawable.ic_notifications));
notif.setColorFilter(MFB.textColor);
notif.setOnClickListener((View v) -> {
mWebView.setVisibility(View.INVISIBLE);
showAnimation = true;
circleRevealView = v;
mWebView.stopLoading();
mWebView.loadUrl(baseURL + "notifications.php");
setTitle(R.string.nav_notifications);
Helpers.uncheckRadioMenu(mNavigationView.getMenu());
//NotificationsService.clearbyId(MainActivity.this, 12);
});
final ImageView msg = action_msg.findViewById(R.id.badge_icon);
setBackground(msg);
msg.setImageDrawable(getResources().getDrawable(R.drawable.ic_message));
msg.setColorFilter(MFB.textColor);
msg.setOnClickListener((View v) -> {
mWebView.setVisibility(View.INVISIBLE);
showAnimation = true;
circleRevealView = v;
mWebView.stopLoading();
mWebView.loadUrl(baseURL + "messages/");
setTitle(R.string.menu_messages);
//NotificationsService.clearbyId(MainActivity.this, 969);
Helpers.uncheckRadioMenu(mNavigationView.getMenu());
});
return true;
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
drawer.closeDrawers();
showAnimation = true;
circleRevealView = null;
mWebView.stopLoading();
// Handle navigation view item clicks here.
switch (item.getItemId()) {
case R.id.nav_top_stories:
mWebView.loadUrl(baseURL + "home.php?sk=h_nor");
setTitle(R.string.menu_top_stories);
return true;
case R.id.nav_most_recent:
mWebView.setVisibility(View.INVISIBLE);
mWebView.loadUrl(baseURL + "home.php?sk=h_chr");
setTitle(R.string.menu_most_recent);
Helpers.uncheckRadioMenu(mNavigationView.getMenu());
return true;
case R.id.nav_friendreq:
mWebView.setVisibility(View.INVISIBLE);
mWebView.loadUrl(baseURL + "friends/center/requests/");
setTitle(R.string.menu_friendreq);
return true;
case R.id.nav_search:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
circleReveal(R.id.searchtoolbar, true);
else
searchToolbar.setVisibility(View.VISIBLE);
searchItem.expandActionView();
return true;
case R.id.nav_groups:
loadCss = true;
showHeader = true;
mWebView.setVisibility(View.INVISIBLE);
mWebView.loadUrl(baseURL + "groups/?category=membership");
return true;
case R.id.nav_mainmenu:
loadCss = true;
showHeader = true;
mWebView.setVisibility(View.INVISIBLE);
if (!sharedPreferences.getBoolean("save_data", false))
mWebView.loadUrl("javascript:(function()%7Btry%7Bdocument.querySelector('%23bookmarks_jewel%20%3E%20a').click()%7Dcatch(_)%7Bwindow.location.href%3D'https%3A%2F%2Fm.facebook.com%2Fhome.php'%7D%7D)()");
else
mWebView.loadUrl("https://mbasic.facebook.com/menu/bookmarks/?ref_component=mbasic_home_header&ref_page=%2Fwap%2Fhome.php&refid=8");
setTitle(R.string.menu_mainmenu);
return true;
case R.id.nav_events:
mWebView.setVisibility(View.INVISIBLE);
mWebView.loadUrl(baseURL + "events/");
return true;
case R.id.nav_photos:
mWebView.setVisibility(View.INVISIBLE);
mWebView.loadUrl(baseURL + "photos/");
return true;
case R.id.nav_settings:
startActivity(new Intent(this, SettingsActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
return true;
default:
return true;
}
}
@JavascriptInterface
@SuppressWarnings("unused")
public void LoadVideo(final String video_url) {
startActivity(new Intent(this, VideoActivity.class).putExtra("video_url", video_url));
}
public void setNotificationNum(int num) {
txtFormat(notif_badge, num, Color.WHITE, false);
}
public void setMessagesNum(int num) {
txtFormat(msg_badge, num, Color.WHITE, false);
}
public void setRequestsNum(int num) {
txtFormat(fr_badge, num, Color.RED, true);
}
public void setMrNum(int num) {
txtFormat(mr_badge, num, Color.RED, true);
}
private void txtFormat(TextView t, int i, int color, boolean bold) {
t.setText(String.format("%s", i));
t.setTextColor(color);
t.setGravity(Gravity.CENTER_VERTICAL);
if (bold)
t.setTypeface(null, Typeface.BOLD);
if (i > 0)
t.setVisibility(View.VISIBLE);
else
t.setVisibility(View.INVISIBLE);
}
private void UrlIntent(Intent intent) {
if (Intent.ACTION_SEND.equals(intent.getAction()) && intent.getType() != null) {
if (URLUtil.isValidUrl(intent.getStringExtra(Intent.EXTRA_TEXT))) {
try {
baseURL = "https://mbasic.facebook.com/composer/?text=" + URLEncoder.encode(intent.getStringExtra(Intent.EXTRA_TEXT), "utf-8");
} catch (UnsupportedEncodingException uee) {
uee.printStackTrace();
}
}
}
if (intent.getExtras() != null && intent.getExtras().containsKey("notifUrl")) {
baseURL = intent.getExtras().getString("notifUrl");
}
if (intent.getDataString() != null) {
baseURL = getIntent().getDataString();
if (intent.getDataString().contains("profile"))
baseURL = baseURL.replace("fb://profile/", "https://facebook.com/");
}
if (Intent.ACTION_SEND.equals(intent.getAction()) && intent.getType() != null) {
if (intent.getType().startsWith("image/") || intent.getType().startsWith("video/") || intent.getType().startsWith("audio/")) {
sharedFromGallery = intent.getParcelableExtra(Intent.EXTRA_STREAM);
// css.append("#MComposer{display:initial}");
baseURL = "https://mbasic.facebook.com";
}
}
mWebView.loadUrl(Helpers.cleanUrl(baseURL));
}
// Thanks to Jaison Fernando for the great tutorial.
// http://droidmentor.com/searchview-animation-like-whatsapp/
private void searchToolbar() {
searchToolbar = findViewById(R.id.searchtoolbar);
searchToolbar.inflateMenu(R.menu.menu_search);
final Menu search_menu = searchToolbar.getMenu();
searchItem = search_menu.findItem(R.id.action_filter_search);
searchView = (SearchView) search_menu.findItem(R.id.action_filter_search).getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
searchView.clearFocus();
mWebView.loadUrl(baseURL + "search/top/?q=" + query);
searchItem.collapseActionView();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
circleReveal(R.id.searchtoolbar, false);
else
searchToolbar.setVisibility(View.INVISIBLE);
return false;
}
@Override
public boolean onQueryTextChange(final String newText) {
return false;
}
});
searchItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
circleReveal(R.id.searchtoolbar, false);
} else
searchToolbar.setVisibility(View.INVISIBLE);
return true;
}
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
return true;
}
});
}
@SuppressWarnings("NewApi")
private void circleReveal(int viewID, final boolean show) {
final View v = findViewById(viewID);
final int cy = v.getHeight() / 2;
Animator anim;
if (show)
anim = ViewAnimationUtils.createCircularReveal(v, v.getWidth(), cy, 0, v.getWidth());
else
anim = ViewAnimationUtils.createCircularReveal(v, v.getWidth(), cy, v.getWidth(), 0);
anim.setDuration(220);
// make the view invisible when the animation is done
anim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (!show) {
super.onAnimationEnd(animation);
v.setVisibility(View.GONE);
}
}
});
// make the view visible and start the animation
if (show)
v.setVisibility(View.VISIBLE);
anim.start();
}
private void setBackground(View btn) {
final TypedValue typedValue = new TypedValue();
int bg;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
bg = android.R.attr.selectableItemBackgroundBorderless;
else
bg = android.R.attr.selectableItemBackground;
getTheme().resolveAttribute(bg, typedValue, true);
btn.setBackgroundResource(typedValue.resourceId);
}
}
| 48,533 | Java | .java | ZeeRooo/MaterialFBook | 139 | 43 | 34 | 2016-09-12T22:22:02Z | 2021-07-18T16:20:04Z |
PhotoActivity.java | /FileExtraction/Java_unseen/ZeeRooo_MaterialFBook/app/src/main/java/me/zeeroooo/materialfb/activities/PhotoActivity.java | package me.zeeroooo.materialfb.activities;
import android.Manifest;
import android.app.DownloadManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.Request;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SizeReadyCallback;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import java.io.File;
import me.zeeroooo.materialfb.R;
import me.zeeroooo.materialfb.ui.CookingAToast;
public class PhotoActivity extends MFBActivity implements View.OnTouchListener {
private ImageView mImageView;
private boolean download = false, countdown = false;
private Matrix matrix = new Matrix(), savedMatrix = new Matrix();
private int NONE = 0, mode = NONE, share = 0;
private PointF start = new PointF(), mid = new PointF();
private float oldDist = 1f;
private View imageTitle, topGradient;
private Toolbar mToolbar;
private String imageUrl;
private WebView webView;
@Override
protected void create(Bundle savedInstanceState) {
super.create(savedInstanceState);
setContentView(R.layout.activity_photo);
mImageView = findViewById(R.id.container);
mImageView.setOnTouchListener(this);
topGradient = findViewById(R.id.photoViewerTopGradient);
mToolbar = findViewById(R.id.toolbar_ph);
setSupportActionBar(mToolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
}
imageTitle = findViewById(R.id.photo_title);
((TextView) imageTitle).setText(getIntent().getStringExtra("title"));
}
@Override
protected void onPostCreate(@Nullable Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
webView = new WebView(this);
webView.getSettings().setBlockNetworkImage(true);
webView.getSettings().setAppCacheEnabled(false);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
if (Build.VERSION.SDK_INT >= 19)
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
else
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webView.loadUrl(getIntent().getStringExtra("link"));
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
imageUrl = url;
Load();
}
});
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
final Window window = getWindow();
window.getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
final int DRAG = 1, ZOOM = 2;
if (!mToolbar.isShown()) {
setVisibility(View.VISIBLE, android.R.anim.fade_in);
setCountDown();
}
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
savedMatrix.set(matrix);
start.set(event.getX(), event.getY());
mode = DRAG;
break;
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
break;
case MotionEvent.ACTION_POINTER_DOWN:
oldDist = spacing(event);
if (oldDist > 5f) {
savedMatrix.set(matrix);
mid.set(event.getX(0) + event.getX(1) / 2, event.getY(0) + event.getY(1) / 2);
mode = ZOOM;
}
break;
case MotionEvent.ACTION_MOVE:
if (mode == DRAG) {
matrix.set(savedMatrix);
matrix.postTranslate(event.getX() - start.x, event.getY() - start.y);
} else if (mode == ZOOM) {
// pinch zooming
float newDist = spacing(event), scale;
if (newDist > 5f) {
matrix.set(savedMatrix);
scale = newDist / oldDist;
matrix.postScale(scale, scale, mid.x, mid.y);
}
}
break;
}
mImageView.setImageMatrix(matrix);
v.performClick();
return true;
}
private float spacing(MotionEvent event) {
final float x = event.getX(0) - event.getX(1);
final float y = event.getY(0) - event.getY(1);
return (float) Math.sqrt(x * x + y * y);
} // https://stackoverflow.com/a/6650484 all the credits to Chirag Raval
private void Load() {
Glide.with(this)
.load(imageUrl)
.listener(new RequestListener<Drawable>() {
@Override
public boolean onLoadFailed(GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
return false;
}
@Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
mImageView.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
findViewById(android.R.id.progress).setVisibility(View.GONE);
setCountDown();
return false;
}
})
.apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE))
.into(mImageView);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.photo, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.download_image:
download = true;
RequestStoragePermission();
break;
case R.id.share_image:
share = 1;
RequestStoragePermission();
break;
case R.id.oopy_url_image:
final ClipboardManager clipboard = (ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE);
final ClipData clip = ClipData.newUri(this.getContentResolver(), "", Uri.parse(imageUrl));
if (clipboard != null)
clipboard.setPrimaryClip(clip);
CookingAToast.cooking(PhotoActivity.this, getString(R.string.content_copy_link_done), Color.WHITE, Color.parseColor("#00C851"), R.drawable.ic_copy_url, true).show();
break;
case android.R.id.home:
onBackPressed();
break;
}
return super.onOptionsItemSelected(item);
}
private void shareImg() {
Glide.with(PhotoActivity.this).asBitmap().load(imageUrl).apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE)).into(new Target<Bitmap>() {
@Override
public void onLoadStarted(@Nullable Drawable placeholder) {
}
@Override
public void onLoadFailed(@Nullable Drawable errorDrawable) {
}
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
final String path = MediaStore.Images.Media.insertImage(getContentResolver(), resource, Uri.parse(imageUrl).getLastPathSegment(), null);
final Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/*");
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(path));
startActivity(Intent.createChooser(shareIntent, getString(R.string.context_share_image)));
CookingAToast.cooking(PhotoActivity.this, getString(R.string.context_share_image_progress), Color.WHITE, Color.parseColor("#00C851"), R.drawable.ic_share, false).show();
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
@Override
public void getSize(@NonNull SizeReadyCallback cb) {
}
@Override
public void removeCallback(@NonNull SizeReadyCallback cb) {
}
@Nullable
@Override
public Request getRequest() {
return null;
}
@Override
public void setRequest(@Nullable Request request) {
}
@Override
public void onStart() {
}
@Override
public void onStop() {
}
@Override
public void onDestroy() {
}
});
share = 2;
}
private void RequestStoragePermission() {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (share == 1)
shareImg();
else if (download) {
// Save the image
final DownloadManager mDownloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
final DownloadManager.Request request = new DownloadManager.Request(Uri.parse(imageUrl));
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, System.currentTimeMillis() + ".jpg");
request.setVisibleInDownloadsUi(true);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
// Start the download
mDownloadManager.enqueue(request);
CookingAToast.cooking(this, getString(R.string.downloaded), Color.WHITE, Color.parseColor("#00C851"), R.drawable.ic_download, false).show();
download = false;
}
} else
CookingAToast.cooking(this, getString(R.string.permission_denied), Color.WHITE, Color.parseColor("#ff4444"), R.drawable.ic_error, true).show();
}
@Override
public void onDestroy() {
super.onDestroy();
if (!(share == 2)) {
if (mImageView != null)
mImageView.setImageDrawable(null);
}
webView.clearCache(true);
webView.clearHistory();
webView.removeAllViews();
webView.destroy();
}
private void setCountDown() {
final CountDownTimer countDownTimer = new CountDownTimer(5000, 1000) {
public void onTick(long millisUntilFinished) {
countdown = true;
}
@Override
public void onFinish() {
setVisibility(View.INVISIBLE, android.R.anim.fade_out);
countdown = false;
}
};
if (!countdown)
countDownTimer.start();
else
countDownTimer.cancel();
}
public void setVisibility(int visibility, int animation) {
final Animation a = AnimationUtils.loadAnimation(this, animation);
topGradient.startAnimation(a);
mToolbar.startAnimation(a);
imageTitle.startAnimation(a);
topGradient.setVisibility(visibility);
mToolbar.setVisibility(visibility);
imageTitle.setVisibility(visibility);
}
} | 13,845 | Java | .java | ZeeRooo/MaterialFBook | 139 | 43 | 34 | 2016-09-12T22:22:02Z | 2021-07-18T16:20:04Z |
MFBActivity.java | /FileExtraction/Java_unseen/ZeeRooo_MaterialFBook/app/src/main/java/me/zeeroooo/materialfb/activities/MFBActivity.java | package me.zeeroooo.materialfb.activities;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.ColorUtils;
import androidx.preference.PreferenceManager;
import java.util.Locale;
import me.zeeroooo.materialfb.MFB;
import me.zeeroooo.materialfb.R;
import me.zeeroooo.materialfb.ui.MFBResources;
@SuppressLint("Registered")
public class MFBActivity extends AppCompatActivity {
protected SharedPreferences sharedPreferences;
private boolean darkTheme;
protected byte themeMode;
private MFBResources mfbResources = null;
@Override
protected void attachBaseContext(Context newBase) {
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(newBase);
super.attachBaseContext(updateResources(newBase));
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
create(savedInstanceState);
}
@Override
public Resources getResources() {
if (mfbResources == null)
mfbResources = new MFBResources(super.getResources());
return mfbResources;
}
protected void create(Bundle savedInstanceState) {
darkTheme = sharedPreferences.getBoolean("darkMode", false);
if (darkTheme)
setTheme(R.style.Black);
super.onCreate(savedInstanceState);
}
private byte getThemeMode() {
if (ColorUtils.calculateLuminance(MFB.colorPrimary) < 0.01 && darkTheme) // dark theme with darker color scheme
return 1;
else if (darkTheme) // dark theme with light color scheme
return 2;
else if (ColorUtils.calculateLuminance(MFB.colorPrimary) < 0.5) // light theme with dark color scheme
return 0;
else if (ColorUtils.calculateLuminance(MFB.colorPrimary) > 0.8) // light theme with bright color scheme
return 3;
else
return 9; // light theme without shinny colors
}
@Override
public void setContentView(int layoutResID) {
themeMode = getThemeMode();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && (themeMode == 2 || themeMode == 3))
getWindow().getDecorView().setSystemUiVisibility(getWindow().getDecorView().getSystemUiVisibility() | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
super.setContentView(layoutResID);
}
private Context updateResources(Context context) {
final Locale locale = new Locale(sharedPreferences.getString("defaultLocale", Locale.getDefault().getLanguage()));
Locale.setDefault(locale);
final Resources resources = context.getResources();
final Configuration config = new Configuration(resources.getConfiguration());
if (Build.VERSION.SDK_INT >= 17) {
config.setLocale(locale);
context = context.createConfigurationContext(config);
} else {
config.locale = locale;
resources.updateConfiguration(config, resources.getDisplayMetrics());
}
return context;
}
}
| 3,341 | Java | .java | ZeeRooo/MaterialFBook | 139 | 43 | 34 | 2016-09-12T22:22:02Z | 2021-07-18T16:20:04Z |
VideoActivity.java | /FileExtraction/Java_unseen/ZeeRooo_MaterialFBook/app/src/main/java/me/zeeroooo/materialfb/activities/VideoActivity.java | package me.zeeroooo.materialfb.activities;
import android.Manifest;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import me.zeeroooo.materialfb.R;
import me.zeeroooo.materialfb.ui.CookingAToast;
public class VideoActivity extends MFBActivity {
private VideoView mVideoView;
private int position = 0;
private RelativeLayout mButtonsHeader;
private SeekBar mSeekbar;
private String url;
private TextView mElapsedTime, mRemainingTime;
private final Runnable Update = new Runnable() {
@Override
public void run() {
if (mSeekbar != null) {
mSeekbar.setProgress(mVideoView.getCurrentPosition());
}
if (mVideoView.isPlaying()) {
mSeekbar.postDelayed(Update, 1000);
mElapsedTime.setText(Time(mVideoView.getCurrentPosition()));
mRemainingTime.setText(Time(mVideoView.getDuration() - mVideoView.getCurrentPosition()));
}
}
};
@Override
protected void create(Bundle savedInstanceState) {
super.create(savedInstanceState);
setContentView(R.layout.activity_video);
url = getIntent().getStringExtra("video_url");
mVideoView = findViewById(R.id.video_view);
mButtonsHeader = findViewById(R.id.buttons_header);
mSeekbar = findViewById(R.id.progress);
mElapsedTime = findViewById(R.id.elapsed_time);
mRemainingTime = findViewById(R.id.remaining_time);
mSeekbar.getProgressDrawable().setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN);
mSeekbar.getThumb().setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN);
mVideoView.setVideoURI(Uri.parse(url));
mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mediaPlayer) {
mVideoView.seekTo(position);
mSeekbar.setMax(mVideoView.getDuration());
mSeekbar.postDelayed(Update, 1000);
mElapsedTime.postDelayed(Update, 1000);
mRemainingTime.postDelayed(Update, 1000);
setVisibility(View.GONE, android.R.anim.fade_out);
if (position == 0)
mVideoView.start();
}
});
}
@Override
protected void onPostCreate(@Nullable Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Buttons
final ImageButton pause = findViewById(R.id.pauseplay_btn);
setBackground(pause);
pause.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (mVideoView.isPlaying()) {
mVideoView.pause();
((ImageButton) v).setImageResource(android.R.drawable.ic_media_play);
} else {
mVideoView.start();
((ImageButton) v).setImageResource(android.R.drawable.ic_media_pause);
}
}
});
final ImageButton previous = findViewById(R.id.previous_btn);
setBackground(previous);
previous.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mVideoView.seekTo(0);
mSeekbar.setProgress(0);
}
});
final ImageButton download = findViewById(R.id.download_btn);
setBackground(download);
download.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
RequestStoragePermission();
}
});
mVideoView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
setCountDown();
setVisibility(View.VISIBLE, android.R.anim.fade_in);
return false;
}
});
final ImageButton share = findViewById(R.id.share_btn);
setBackground(share);
share.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, url);
startActivity(Intent.createChooser(shareIntent, getString(R.string.context_share_link)));
}
});
mSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser)
mVideoView.seekTo(progress);
}
});
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
final Window window = getWindow();
window.getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
}
private String Time(long ms) {
return String.format(Locale.getDefault(), "%d:%d", TimeUnit.MILLISECONDS.toMinutes(ms), TimeUnit.MILLISECONDS.toSeconds(ms) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((ms))));
}
private void RequestStoragePermission() {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
final DownloadManager mDownloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
final DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_MOVIES, System.currentTimeMillis() + url.substring(url.indexOf("_n") + 2).split("\\?_")[0]);
request.setVisibleInDownloadsUi(true);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
// Start the download
mDownloadManager.enqueue(request);
CookingAToast.cooking(this, getString(R.string.downloaded), Color.WHITE, Color.parseColor("#00C851"), R.drawable.ic_download, false).show();
} else
CookingAToast.cooking(this, getString(R.string.permission_denied), Color.WHITE, Color.parseColor("#ff4444"), R.drawable.ic_error, true).show();
}
@Override
public void onPause() {
super.onPause();
position = mVideoView.getCurrentPosition();
mVideoView.pause();
}
@Override
protected void onResume() {
super.onResume();
mVideoView.seekTo(position);
mVideoView.start();
}
private void setCountDown() {
new CountDownTimer(5000, 1000) {
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
setVisibility(View.INVISIBLE, android.R.anim.fade_out);
}
}.start();
}
public void setVisibility(int visibility, int animation) {
mButtonsHeader.startAnimation(AnimationUtils.loadAnimation(this, animation));
mButtonsHeader.setVisibility(visibility);
}
private void setBackground(View btn) {
final TypedValue typedValue = new TypedValue();
int bg;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
bg = android.R.attr.selectableItemBackgroundBorderless;
else
bg = android.R.attr.selectableItemBackground;
getTheme().resolveAttribute(bg, typedValue, true);
btn.setBackgroundResource(typedValue.resourceId);
}
}
| 9,436 | Java | .java | ZeeRooo/MaterialFBook | 139 | 43 | 34 | 2016-09-12T22:22:02Z | 2021-07-18T16:20:04Z |
AdapterBookmarks.java | /FileExtraction/Java_unseen/ZeeRooo_MaterialFBook/app/src/main/java/me/zeeroooo/materialfb/adapters/AdapterBookmarks.java | package me.zeeroooo.materialfb.adapters;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import me.zeeroooo.materialfb.R;
import me.zeeroooo.materialfb.misc.DatabaseHelper;
import me.zeeroooo.materialfb.misc.ModelBookmarks;
import me.zeeroooo.materialfb.ui.CookingAToast;
public class AdapterBookmarks extends ArrayAdapter<ModelBookmarks> {
private ArrayList<ModelBookmarks> bookmarks;
private DatabaseHelper DBHelper;
private ModelBookmarks modelBookmarks;
private ViewHolder viewHolder;
private LayoutInflater layoutInflater;
public AdapterBookmarks(Context context, ArrayList<ModelBookmarks> bk, DatabaseHelper db) {
super(context, R.layout.bookmarks_listview, bk);
this.bookmarks = bk;
this.DBHelper = db;
}
private static class ViewHolder {
private TextView title;
private ImageButton delete, share;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
modelBookmarks = getItem(position);
if (convertView == null) {
viewHolder = new ViewHolder();
layoutInflater = LayoutInflater.from(getContext());
convertView = layoutInflater.inflate(R.layout.bookmarks_listview, parent, false);
viewHolder.title = convertView.findViewById(R.id.bookmark_title);
viewHolder.delete = convertView.findViewById(R.id.delete_bookmark);
viewHolder.share = convertView.findViewById(R.id.share_bookmark);
setBackground(viewHolder.share);
setBackground(viewHolder.delete);
viewHolder.share.setColorFilter(viewHolder.title.getCurrentTextColor());
viewHolder.delete.setColorFilter(viewHolder.title.getCurrentTextColor());
// Cache the viewHolder object inside the fresh view
convertView.setTag(viewHolder);
} else
viewHolder = (ViewHolder) convertView.getTag();
viewHolder.title.setText(modelBookmarks.getTitle());
viewHolder.delete.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
DBHelper.remove(modelBookmarks.getTitle(), modelBookmarks.getUrl(), null);
bookmarks.remove(position);
notifyDataSetChanged();
CookingAToast.cooking(getContext(), getContext().getString(R.string.remove_bookmark) + " " + modelBookmarks.getTitle(), Color.WHITE, Color.parseColor("#fcd90f"), R.drawable.ic_delete, false).show();
}
});
viewHolder.share.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, modelBookmarks.getUrl());
getContext().startActivity(Intent.createChooser(shareIntent, getContext().getString(R.string.context_share_link)));
}
});
return convertView;
}
private void setBackground(ImageButton btn) {
final TypedValue typedValue = new TypedValue();
int bg;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
bg = android.R.attr.selectableItemBackgroundBorderless;
else
bg = android.R.attr.selectableItemBackground;
getContext().getTheme().resolveAttribute(bg, typedValue, true);
btn.setBackgroundResource(typedValue.resourceId);
}
} | 3,958 | Java | .java | ZeeRooo/MaterialFBook | 139 | 43 | 34 | 2016-09-12T22:22:02Z | 2021-07-18T16:20:04Z |
AdapterListPreference.java | /FileExtraction/Java_unseen/ZeeRooo_MaterialFBook/app/src/main/java/me/zeeroooo/materialfb/adapters/AdapterListPreference.java | package me.zeeroooo.materialfb.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.graphics.BlendModeColorFilterCompat;
import androidx.core.graphics.BlendModeCompat;
import androidx.preference.ListPreference;
import me.zeeroooo.materialfb.MFB;
import me.zeeroooo.materialfb.R;
public class AdapterListPreference extends ArrayAdapter<CharSequence> {
private String defaultValue;
private CharSequence charSequence;
private ViewHolder viewHolder;
private LayoutInflater layoutInflater;
public AdapterListPreference(Context context, ListPreference listPreference) {
super(context, R.layout.bookmarks_listview, listPreference.getEntries());
defaultValue = listPreference.getValue();
}
public AdapterListPreference(Context context, CharSequence[] charSequences) {
super(context, R.layout.bookmarks_listview, charSequences);
defaultValue = "";
}
private static class ViewHolder {
private CheckedTextView checkedTextView;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
charSequence = getItem(position);
if (convertView == null) {
viewHolder = new ViewHolder();
layoutInflater = LayoutInflater.from(getContext());
convertView = layoutInflater.inflate(android.R.layout.simple_list_item_single_choice, parent, false);
viewHolder.checkedTextView = convertView.findViewById(android.R.id.text1);
convertView.setTag(viewHolder);
} else
viewHolder = (ViewHolder) convertView.getTag();
viewHolder.checkedTextView.setText(charSequence);
viewHolder.checkedTextView.setChecked(defaultValue.contentEquals(charSequence));
viewHolder.checkedTextView.getCheckMarkDrawable().setColorFilter(BlendModeColorFilterCompat.createBlendModeColorFilterCompat(MFB.colorAccent, BlendModeCompat.SRC_ATOP));
return convertView;
}
}
| 2,253 | Java | .java | ZeeRooo/MaterialFBook | 139 | 43 | 34 | 2016-09-12T22:22:02Z | 2021-07-18T16:20:04Z |
MFBRingtoneDialog.java | /FileExtraction/Java_unseen/ZeeRooo_MaterialFBook/app/src/main/java/me/zeeroooo/materialfb/ui/MFBRingtoneDialog.java | package me.zeeroooo.materialfb.ui;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.widget.Button;
import androidx.appcompat.app.AlertDialog;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import java.io.IOException;
import me.zeeroooo.materialfb.MFB;
import me.zeeroooo.materialfb.R;
import me.zeeroooo.materialfb.adapters.AdapterListPreference;
public class MFBRingtoneDialog extends MaterialAlertDialogBuilder {
private MediaPlayer mediaPlayer;
private short position = 0;
private Button button = null;
public MFBRingtoneDialog(Context context, SharedPreferences sharedPreferences, String type) {
super(context, R.style.ThemeOverlay_MaterialComponents_Dialog_Alert);
final RingtoneManager ringtoneManager = new RingtoneManager(context);
ringtoneManager.setType(RingtoneManager.TYPE_NOTIFICATION);
final Cursor cursor = ringtoneManager.getCursor();
final CharSequence[] titleCharSequences = new CharSequence[cursor.getCount()], uriCharSequences = new CharSequence[cursor.getCount()];
while (cursor.moveToNext()) {
titleCharSequences[position] = cursor.getString(RingtoneManager.TITLE_COLUMN_INDEX);
uriCharSequences[position] = cursor.getString(RingtoneManager.URI_COLUMN_INDEX) + '/' + cursor.getString(RingtoneManager.ID_COLUMN_INDEX);
position++;
}
cursor.close();
mediaPlayer = new MediaPlayer();
mediaPlayer.setLooping(false);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
mediaPlayer.setOnCompletionListener(MediaPlayer::release);
CharSequence defaultValue = Uri.parse(sharedPreferences.getString(type, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION).toString())).toString();
for (position = 0; position < uriCharSequences.length; position++)
if (defaultValue.equals(uriCharSequences[position]))
break;
setSingleChoiceItems(new AdapterListPreference(context, titleCharSequences), position, (dialogInterface, i) -> {
position = (short) i;
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(context, Uri.parse(uriCharSequences[i].toString()));
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
mediaPlayer.release();
}
mediaPlayer.start();
});
setPositiveButton(context.getString(android.R.string.ok), (dialogInterface, i) -> {
sharedPreferences.edit().putString(type, uriCharSequences[position].toString()).apply();
dialogInterface.dismiss();
});
setOnDismissListener(dialogInterface -> mediaPlayer.release());
}
@Override
public AlertDialog show() {
final AlertDialog alertDialog = super.show();
for (byte a = -3; a < 0; a++) {
button = alertDialog.getButton(a);
if (button != null)
button.setTextColor(MFB.colorPrimary);
}
return alertDialog;
}
}
| 3,349 | Java | .java | ZeeRooo/MaterialFBook | 139 | 43 | 34 | 2016-09-12T22:22:02Z | 2021-07-18T16:20:04Z |
MFBFloatingActionButton.java | /FileExtraction/Java_unseen/ZeeRooo_MaterialFBook/app/src/main/java/me/zeeroooo/materialfb/ui/MFBFloatingActionButton.java | package me.zeeroooo.materialfb.ui;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.LinearLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import me.zeeroooo.materialfb.MFB;
import me.zeeroooo.materialfb.R;
public class MFBFloatingActionButton extends LinearLayout {
private byte id;
private boolean shown = true;
private FloatingActionButton floatingActionButton;
private LayoutParams layoutParams;
public MFBFloatingActionButton(@NonNull Context context) {
super(context);
init();
}
public MFBFloatingActionButton(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public MFBFloatingActionButton(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
setOrientation(VERTICAL);
layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(0, 0, 16, 16);
addButton(getResources().getDrawable(R.drawable.ic_fab_menu), "", FloatingActionButton.SIZE_NORMAL, view -> {
for (id = (byte) (getChildCount() - 1); id > 0; id--) {
if (shown)
((FloatingActionButton) findViewById(id)).hide();
else
((FloatingActionButton) findViewById(id)).show();
}
shown = !shown;
});
}
public void show() {
if (!shown) {
((FloatingActionButton) findViewById(0)).show();
shown = true;
}
}
public void hide() {
if (shown) {
floatingActionButton = findViewById(0);
floatingActionButton.performClick();
floatingActionButton.hide();
}
}
public void addButton(Drawable icon, String description, int size, OnClickListener onClickListener) {
floatingActionButton = new FloatingActionButton(getContext());
floatingActionButton.setImageDrawable(icon);
floatingActionButton.setBackgroundTintList(ColorStateList.valueOf(MFB.colorAccent));
floatingActionButton.setColorFilter(MFB.colorAccent == Color.WHITE ? MFB.colorPrimary : Color.WHITE);
floatingActionButton.setOnClickListener(onClickListener);
floatingActionButton.setSize(size);
floatingActionButton.setContentDescription(description);
floatingActionButton.setId(id);
floatingActionButton.setLayoutParams(layoutParams);
addView(floatingActionButton, 0);
id++;
}
}
| 2,895 | Java | .java | ZeeRooo/MaterialFBook | 139 | 43 | 34 | 2016-09-12T22:22:02Z | 2021-07-18T16:20:04Z |
MFBResources.java | /FileExtraction/Java_unseen/ZeeRooo_MaterialFBook/app/src/main/java/me/zeeroooo/materialfb/ui/MFBResources.java | package me.zeeroooo.materialfb.ui;
import android.content.SharedPreferences;
import android.content.res.Resources;
import me.zeeroooo.materialfb.MFB;
import me.zeeroooo.materialfb.R;
public class MFBResources extends Resources {
public MFBResources(Resources r) {
super(r.getAssets(), r.getDisplayMetrics(), r.getConfiguration());
}
@Override
public int getColor(int id, Theme theme) throws NotFoundException {
switch (getResourceEntryName(id)) {
case "colorPrimary":
return MFB.colorPrimary;
case "colorPrimaryDark":
return MFB.colorPrimaryDark;
case "colorAccent":
return MFB.colorAccent;
default:
return super.getColor(id, theme);
}
}
public void setColors(SharedPreferences sharedPreferences) {
MFB.colorPrimary = sharedPreferences.getInt("colorPrimary", R.color.colorPrimary);
MFB.colorPrimaryDark = sharedPreferences.getInt("colorPrimaryDark", R.color.colorPrimaryDark);
MFB.colorAccent = sharedPreferences.getInt("colorAccent", R.color.colorAccent);
}
}
| 1,155 | Java | .java | ZeeRooo/MaterialFBook | 139 | 43 | 34 | 2016-09-12T22:22:02Z | 2021-07-18T16:20:04Z |
MFBPreferenceCategory.java | /FileExtraction/Java_unseen/ZeeRooo_MaterialFBook/app/src/main/java/me/zeeroooo/materialfb/ui/MFBPreferenceCategory.java | package me.zeeroooo.materialfb.ui;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
import androidx.preference.PreferenceCategory;
import androidx.preference.PreferenceViewHolder;
import me.zeeroooo.materialfb.MFB;
public class MFBPreferenceCategory extends PreferenceCategory {
public MFBPreferenceCategory(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public MFBPreferenceCategory(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MFBPreferenceCategory(Context context) {
super(context);
}
@Override
public void onBindViewHolder(PreferenceViewHolder holder) {
super.onBindViewHolder(holder);
((TextView) holder.findViewById(android.R.id.title)).setTextColor(MFB.colorAccent);
}
}
| 887 | Java | .java | ZeeRooo/MaterialFBook | 139 | 43 | 34 | 2016-09-12T22:22:02Z | 2021-07-18T16:20:04Z |
MFBSwitchPreference.java | /FileExtraction/Java_unseen/ZeeRooo_MaterialFBook/app/src/main/java/me/zeeroooo/materialfb/ui/MFBSwitchPreference.java | package me.zeeroooo.materialfb.ui;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Switch;
import androidx.preference.PreferenceViewHolder;
import androidx.preference.SwitchPreference;
import me.zeeroooo.materialfb.MFB;
public class MFBSwitchPreference extends SwitchPreference {
private Switch aSwitch, tempSwitch;
private View view;
public MFBSwitchPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public MFBSwitchPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MFBSwitchPreference(Context context) {
super(context);
}
@Override
public void onBindViewHolder(PreferenceViewHolder holder) {
super.onBindViewHolder(holder);
aSwitch = findSwitchInChildViews((ViewGroup) holder.itemView);
if (aSwitch != null) {
changeColor(aSwitch.isChecked());
aSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> changeColor(isChecked));
}
}
private Switch findSwitchInChildViews(ViewGroup viewGroup) {
for (int i = 0; i < viewGroup.getChildCount(); i++) {
view = viewGroup.getChildAt(i);
if (view instanceof Switch)
return (Switch) view;
else if (view instanceof ViewGroup) {
tempSwitch = findSwitchInChildViews((ViewGroup) view);
if (tempSwitch != null)
return tempSwitch;
}
}
return null;
}
private void changeColor(boolean checked) {
try {
aSwitch.getThumbDrawable().setColorFilter(checked ? MFB.colorAccent : Color.parseColor("#ECECEC"), PorterDuff.Mode.SRC_ATOP);
aSwitch.getTrackDrawable().setColorFilter(checked ? MFB.colorPrimaryDark : Color.parseColor("#B9B9B9"), PorterDuff.Mode.SRC_ATOP);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
| 2,166 | Java | .java | ZeeRooo/MaterialFBook | 139 | 43 | 34 | 2016-09-12T22:22:02Z | 2021-07-18T16:20:04Z |
MFBDialog.java | /FileExtraction/Java_unseen/ZeeRooo_MaterialFBook/app/src/main/java/me/zeeroooo/materialfb/ui/MFBDialog.java | package me.zeeroooo.materialfb.ui;
import android.content.Context;
import android.widget.Button;
import androidx.appcompat.app.AlertDialog;
import androidx.preference.ListPreference;
import androidx.preference.Preference;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import me.zeeroooo.materialfb.MFB;
import me.zeeroooo.materialfb.R;
import me.zeeroooo.materialfb.adapters.AdapterListPreference;
public class MFBDialog extends MaterialAlertDialogBuilder {
private Button button = null;
public MFBDialog(Context context, int overrideThemeResId) {
super(context, overrideThemeResId);
}
public MFBDialog(Context context) {
super(context, R.style.ThemeOverlay_MaterialComponents_Dialog_Alert);
}
public MFBDialog(Context context, Preference preference) {
super(context, R.style.ThemeOverlay_MaterialComponents_Dialog_Alert);
final ListPreference listPreference = (ListPreference) preference;
final CharSequence[] valuesArray = listPreference.getEntryValues();
setSingleChoiceItems(listPreference.getEntries(), listPreference.findIndexOfValue(listPreference.getValue()), null);
setAdapter(new AdapterListPreference(getContext(), listPreference), (dialogInterface, i) -> {
String value = valuesArray[i].toString();
if (listPreference.callChangeListener(value))
listPreference.setValue(value);
dialogInterface.dismiss();
});
setPositiveButton(null, null);
}
@Override
public AlertDialog show() {
final AlertDialog alertDialog = super.show();
for (byte a = -3; a < 0; a++) {
button = alertDialog.getButton(a);
if (button != null)
button.setTextColor(MFB.colorPrimary);
}
return alertDialog;
}
}
| 1,868 | Java | .java | ZeeRooo/MaterialFBook | 139 | 43 | 34 | 2016-09-12T22:22:02Z | 2021-07-18T16:20:04Z |
CookingAToast.java | /FileExtraction/Java_unseen/ZeeRooo_MaterialFBook/app/src/main/java/me/zeeroooo/materialfb/ui/CookingAToast.java | /*
* Created by ZeeRooo
* https://github.com/ZeeRooo
*/
package me.zeeroooo.materialfb.ui;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.CheckResult;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;
import me.zeeroooo.materialfb.R;
public class CookingAToast {
public static @CheckResult
Toast cooking(Context context, CharSequence message_to_show, int text_color, int background, int icon_toast, boolean duration) {
View view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.cooking_a_toast, null);
view.setBackgroundColor(background);
AppCompatImageView icon = view.findViewById(R.id.icon);
icon.setImageResource(icon_toast);
AppCompatTextView message = view.findViewById(R.id.message);
message.setText(message_to_show);
message.setTextColor(text_color);
Toast toast = new Toast(context);
toast.setView(view);
toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.BOTTOM, 0, 0);
if (duration) {
toast.setDuration(Toast.LENGTH_LONG);
} else {
toast.setDuration(Toast.LENGTH_SHORT);
}
return toast;
}
} | 1,398 | Java | .java | ZeeRooo/MaterialFBook | 139 | 43 | 34 | 2016-09-12T22:22:02Z | 2021-07-18T16:20:04Z |
NotificationsSettingsFragment.java | /FileExtraction/Java_unseen/ZeeRooo_MaterialFBook/app/src/main/java/me/zeeroooo/materialfb/fragments/NotificationsSettingsFragment.java | /*
* Code taken from FaceSlim by indywidualny. Thanks.
*/
package me.zeeroooo.materialfb.fragments;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import androidx.appcompat.app.AlertDialog;
import androidx.preference.Preference;
import androidx.preference.PreferenceManager;
import androidx.work.Constraints;
import androidx.work.NetworkType;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkManager;
import com.google.android.material.chip.Chip;
import com.google.android.material.chip.ChipGroup;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import me.zeeroooo.materialfb.MFB;
import me.zeeroooo.materialfb.R;
import me.zeeroooo.materialfb.misc.DatabaseHelper;
import me.zeeroooo.materialfb.notifications.NotificationsService;
import me.zeeroooo.materialfb.ui.MFBDialog;
import me.zeeroooo.materialfb.ui.MFBRingtoneDialog;
public class NotificationsSettingsFragment extends MFBPreferenceFragment implements Preference.OnPreferenceClickListener {
private SharedPreferences sharedPreferences;
private DatabaseHelper DBHelper;
private ArrayList<String> blacklist = new ArrayList<>();
private WorkManager workManager;
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
addPreferencesFromResource(R.xml.notifications_settings);
workManager = WorkManager.getInstance();
if (getActivity() != null) {
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
DBHelper = new DatabaseHelper(getActivity());
findPreference("BlackList").setOnPreferenceClickListener(this);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
findPreference("ringtone").setOnPreferenceClickListener(this);
findPreference("ringtone_msg").setOnPreferenceClickListener(this);
} else
findPreference("notification_channel_shortcut").setOnPreferenceClickListener(this);
sharedPreferences.registerOnSharedPreferenceChangeListener((prefs, key) -> {
switch (key) {
case "notif_interval":
workManager.cancelAllWork();
workManager.enqueue(new PeriodicWorkRequest.Builder(NotificationsService.class, Integer.valueOf(prefs.getString("notif_interval", "60000")), TimeUnit.MILLISECONDS)
.setConstraints(new Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build())
.build());
break;
default:
break;
}
});
}
}
@Override
public void onStop() {
super.onStop();
DBHelper.close();
}
@Override
public boolean onPreferenceClick(Preference preference) {
switch (preference.getKey()) {
case "notification_channel_shortcut":
startActivity(new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS).putExtra(Settings.EXTRA_APP_PACKAGE, getActivity().getPackageName()));
break;
case "ringtone":
case "ringtone_msg":
new MFBRingtoneDialog(getActivity(), sharedPreferences, preference.getKey()).show();
break;
case "BlackList":
AlertDialog blacklistDialog = new MFBDialog(getActivity()).create();
blacklistDialog.setTitle(R.string.blacklist_title);
final View rootView = LayoutInflater.from(getActivity()).inflate(R.layout.chip_input, null);
final Cursor cursor = DBHelper.getReadableDatabase().rawQuery("SELECT BL FROM mfb_table", null);
while (cursor.moveToNext()) {
if (cursor.getString(0) != null)
addRemovableChip(cursor.getString(0), rootView);
}
final AutoCompleteTextView autoCompleteTextView = rootView.findViewById(R.id.preloadedTags);
autoCompleteTextView.setAdapter(new ArrayAdapter<>(rootView.getContext(), android.R.layout.simple_dropdown_item_1line));
autoCompleteTextView.setOnItemClickListener((parent, view, position, id) -> {
addRemovableChip((String) parent.getItemAtPosition(position), rootView);
autoCompleteTextView.setText("");
});
autoCompleteTextView.setOnEditorActionListener((v, actionId, event) -> {
if ((actionId == EditorInfo.IME_ACTION_DONE)) {
addRemovableChip(v.getText().toString(), rootView);
autoCompleteTextView.setText("");
return true;
} else
return false;
});
blacklistDialog.setButton(DialogInterface.BUTTON_POSITIVE, getText(android.R.string.ok), (dialog, which) -> {
for (int position = 0; position < blacklist.size(); position++) {
DBHelper.addData(null, null, blacklist.get(position));
}
blacklist.clear();
if (!cursor.isClosed()) {
cursor.close();
}
});
blacklistDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getText(android.R.string.cancel), (dialog, which) -> {
blacklistDialog.dismiss();
blacklist.clear();
if (!cursor.isClosed()) {
cursor.close();
}
});
blacklistDialog.setView(rootView);
blacklistDialog.show();
return true;
}
return false;
}
private void addRemovableChip(String text, final View rootView) {
blacklist.add(text);
Chip chip = new Chip(rootView.getContext());
chip.setChipBackgroundColor(ColorStateList.valueOf(MFB.colorAccent));
// chip.setChipBackgroundColor(ColorStateList.valueOf(Theme.getColor(getActivity())));
chip.setTextColor(MFB.textColor);
chip.setText(text);
chip.setTag(text);
chip.setCloseIconVisible(true);
((ChipGroup) rootView.findViewById(R.id.tagsChipGroup)).addView(chip);
chip.setOnCloseIconClickListener(v -> {
((ChipGroup) rootView.findViewById(R.id.tagsChipGroup)).removeView(v);
blacklist.remove(v.getTag());
DBHelper.remove(null, null, v.getTag().toString());
});
}
} | 7,154 | Java | .java | ZeeRooo/MaterialFBook | 139 | 43 | 34 | 2016-09-12T22:22:02Z | 2021-07-18T16:20:04Z |
NavigationMenuFragment.java | /FileExtraction/Java_unseen/ZeeRooo_MaterialFBook/app/src/main/java/me/zeeroooo/materialfb/fragments/NavigationMenuFragment.java | package me.zeeroooo.materialfb.fragments;
import android.os.Bundle;
import me.zeeroooo.materialfb.R;
public class NavigationMenuFragment extends MFBPreferenceFragment {
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
addPreferencesFromResource(R.xml.navigation_menu_settings);
}
} | 343 | Java | .java | ZeeRooo/MaterialFBook | 139 | 43 | 34 | 2016-09-12T22:22:02Z | 2021-07-18T16:20:04Z |
MoreAndCreditsFragment.java | /FileExtraction/Java_unseen/ZeeRooo_MaterialFBook/app/src/main/java/me/zeeroooo/materialfb/fragments/MoreAndCreditsFragment.java | package me.zeeroooo.materialfb.fragments;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Html;
import androidx.appcompat.app.AlertDialog;
import androidx.preference.Preference;
import me.zeeroooo.materialfb.BuildConfig;
import me.zeeroooo.materialfb.R;
import me.zeeroooo.materialfb.ui.MFBDialog;
public class MoreAndCreditsFragment extends MFBPreferenceFragment implements Preference.OnPreferenceClickListener {
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
addPreferencesFromResource(R.xml.more);
findPreference("changelog").setOnPreferenceClickListener(this);
findPreference("mfb_version").setSummary(getString(R.string.updates_summary, BuildConfig.VERSION_NAME));
}
@Override
public boolean onPreferenceClick(Preference preference) {
switch (preference.getKey()) {
case "changelog":
final AlertDialog changelog = new MFBDialog(getActivity()).create();
changelog.setTitle(getResources().getString(R.string.changelog));
changelog.setMessage(Html.fromHtml(getResources().getString(R.string.changelog_list)));
changelog.setCancelable(false);
changelog.setButton(DialogInterface.BUTTON_POSITIVE, getText(android.R.string.ok), (dialogInterface, i) -> changelog.dismiss());
changelog.show();
return true;
}
return false;
}
} | 1,502 | Java | .java | ZeeRooo/MaterialFBook | 139 | 43 | 34 | 2016-09-12T22:22:02Z | 2021-07-18T16:20:04Z |
SettingsFragment.java | /FileExtraction/Java_unseen/ZeeRooo_MaterialFBook/app/src/main/java/me/zeeroooo/materialfb/fragments/SettingsFragment.java | /**
* Code taken from FaceSlim by indywidualny. Thanks.
**/
package me.zeeroooo.materialfb.fragments;
import android.Manifest;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.text.InputFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.graphics.ColorUtils;
import androidx.preference.Preference;
import androidx.preference.PreferenceManager;
import androidx.work.Constraints;
import androidx.work.NetworkType;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkManager;
import com.google.android.material.slider.Slider;
import com.google.android.material.switchmaterial.SwitchMaterial;
import java.util.concurrent.TimeUnit;
import me.zeeroooo.materialfb.MFB;
import me.zeeroooo.materialfb.R;
import me.zeeroooo.materialfb.notifications.NotificationsService;
import me.zeeroooo.materialfb.ui.CookingAToast;
import me.zeeroooo.materialfb.ui.MFBDialog;
public class SettingsFragment extends MFBPreferenceFragment implements Preference.OnPreferenceClickListener {
private SharedPreferences mPreferences;
private WorkManager workManager;
private int red = 1, green = 1, blue = 1, colorPrimary;
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
addPreferencesFromResource(R.xml.settings);
mPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
workManager = WorkManager.getInstance();
// set onPreferenceClickListener for a few preferences
findPreference("notifications_settings").setOnPreferenceClickListener(this);
findPreference("navigation_menu_settings").setOnPreferenceClickListener(this);
findPreference("more_and_credits").setOnPreferenceClickListener(this);
findPreference("location_enabled").setOnPreferenceClickListener(this);
findPreference("save_data").setOnPreferenceClickListener(this);
findPreference("notif").setOnPreferenceClickListener(this);
findPreference("color_picker").setOnPreferenceClickListener(this);
findPreference("localeSwitcher").setOnPreferenceChangeListener((preference, o) -> {
mPreferences.edit().putString("defaultLocale", o.toString()).apply();
getActivity().recreate();
return true;
});
}
@Override
public boolean onPreferenceClick(Preference preference) {
switch (preference.getKey()) {
case "notifications_settings":
getFragmentManager().beginTransaction()
.addToBackStack(null).replace(R.id.content_frame,
new NotificationsSettingsFragment()).commit();
return true;
case "navigation_menu_settings":
getFragmentManager().beginTransaction()
.addToBackStack(null).replace(R.id.content_frame,
new NavigationMenuFragment()).commit();
return true;
case "more_and_credits":
getFragmentManager().beginTransaction()
.addToBackStack(null).replace(R.id.content_frame,
new MoreAndCreditsFragment()).commit();
return true;
case "location_enabled":
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
return true;
case "save_data":
case "notif":
setScheduler();
return true;
case "color_picker":
final AlertDialog mfbColorPickerDialog = new MFBDialog(getActivity()).create();
final TextView previewTextView = new TextView(getActivity());
previewTextView.setTextAppearance(getActivity(), R.style.MaterialAlertDialog_MaterialComponents_Title_Text);
previewTextView.setTextSize(22.0f);
previewTextView.setText(R.string.color_picker_title);
previewTextView.setPadding(24, 21, 24, 21);
previewTextView.setBackgroundColor(Color.BLACK);
mfbColorPickerDialog.setCustomTitle(previewTextView);
final View rootView = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_color_picker, null);
final EditText hexColorInput = rootView.findViewById(R.id.color_picker_hex);
final Slider sliderRed = rootView.findViewById(R.id.color_picker_red_slider), sliderGreen = rootView.findViewById(R.id.color_picker_green_slider), sliderBlue = rootView.findViewById(R.id.color_picker_blue_slider);
sliderRed.addOnChangeListener((slider, value, fromUser) -> {
red = (int) value;
setColor(previewTextView, hexColorInput);
});
sliderGreen.addOnChangeListener((slider, value, fromUser) -> {
green = (int) value;
setColor(previewTextView, hexColorInput);
});
sliderBlue.addOnChangeListener((slider, value, fromUser) -> {
blue = (int) value;
setColor(previewTextView, hexColorInput);
});
hexColorInput.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});
hexColorInput.setOnEditorActionListener((textView, i, keyEvent) -> {
colorPrimary = Color.parseColor("#" + textView.getText().toString().replace("#", ""));
previewTextView.setBackgroundColor(colorPrimary);
red = Color.red(colorPrimary);
green = Color.green(colorPrimary);
blue = Color.blue(colorPrimary);
sliderRed.setValue(red);
sliderGreen.setValue(green);
sliderBlue.setValue(blue);
return true;
});
final SwitchMaterial switchMaterial = rootView.findViewById(R.id.color_picker_dark_mode);
switchMaterial.setOnCheckedChangeListener((compoundButton, b) -> {
switchMaterial.getThumbDrawable().setColorFilter(b ? MFB.colorAccent : Color.parseColor("#ECECEC"), PorterDuff.Mode.SRC_ATOP);
switchMaterial.getTrackDrawable().setColorFilter(b ? MFB.colorPrimaryDark : Color.parseColor("#B9B9B9"), PorterDuff.Mode.SRC_ATOP);
});
mfbColorPickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(android.R.string.cancel), (dialogInterface, i) -> mfbColorPickerDialog.dismiss());
mfbColorPickerDialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(android.R.string.ok), (dialogInterface, i) -> {
mfbColorPickerDialog.dismiss();
colorPrimary = Color.rgb(red, green, blue);
int colorAccent;
if (ColorUtils.calculateLuminance(colorPrimary) > 0.8 || (ColorUtils.calculateLuminance(MFB.colorPrimary) < 0.5 && switchMaterial.isChecked())) // it's too bright
colorAccent = Color.BLACK;
else if (ColorUtils.calculateLuminance(colorPrimary) < 0.01 && switchMaterial.isChecked()) // it's too dark
colorAccent = Color.WHITE;
else
colorAccent = colorLighter(colorPrimary);
mPreferences.edit().putInt("colorPrimary", colorPrimary).apply();
mPreferences.edit().putInt("colorPrimaryDark", colorDarker(colorPrimary)).apply();
mPreferences.edit().putInt("colorAccent", colorAccent).apply();
mPreferences.edit().putBoolean("darkMode", switchMaterial.isChecked()).apply();
getActivity().recreate();
//CookingAToast.cooking(getActivity(), getString(R.string.required_restart), Color.WHITE, colorPrimary, R.drawable.ic_error, true).show();
});
mfbColorPickerDialog.setView(rootView);
mfbColorPickerDialog.show();
return true;
default:
return false;
}
}
private void setColor(TextView textView, EditText hexColorInput) {
colorPrimary = Color.rgb(red, green, blue);
textView.setBackgroundColor(colorPrimary);
hexColorInput.setText(Integer.toHexString(colorPrimary).substring(2));
}
private float[] hsv = new float[3];
private int colorDarker(int color) {
Color.colorToHSV(color, hsv);
hsv[2] *= 0.8f; // smaller = darker
return Color.HSVToColor(hsv);
}
private int colorLighter(int color) {
Color.colorToHSV(color, hsv);
hsv[2] /= 0.8f;
return Color.HSVToColor(hsv);
}
private void setScheduler() {
if (mPreferences.getBoolean("notif", false) && !mPreferences.getBoolean("save_data", false))
workManager.enqueue(new PeriodicWorkRequest.Builder(NotificationsService.class, Integer.valueOf(mPreferences.getString("notif_interval", "60000")), TimeUnit.MILLISECONDS)
.setConstraints(new Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build())
.build());
else
workManager.cancelAllWork();
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (!(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED))
CookingAToast.cooking(getActivity(), getString(R.string.permission_denied), Color.WHITE, Color.parseColor("#ff4444"), R.drawable.ic_error, true).show();
}
} | 10,145 | Java | .java | ZeeRooo/MaterialFBook | 139 | 43 | 34 | 2016-09-12T22:22:02Z | 2021-07-18T16:20:04Z |
MFBPreferenceFragment.java | /FileExtraction/Java_unseen/ZeeRooo_MaterialFBook/app/src/main/java/me/zeeroooo/materialfb/fragments/MFBPreferenceFragment.java | package me.zeeroooo.materialfb.fragments;
import android.os.Bundle;
import androidx.preference.ListPreference;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import me.zeeroooo.materialfb.ui.MFBDialog;
public class MFBPreferenceFragment extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
}
@Override
public void onDisplayPreferenceDialog(Preference preference) {
if (preference instanceof ListPreference) {
new MFBDialog(getActivity(), preference).show();
/* DialogFragment dialogFragment = new MFBPreferenceDialog(preference);// MFBPreferenceDialog.newInstance(preference);
dialogFragment.setTargetFragment(this, 0);
dialogFragment.show(getFragmentManager(), null);*/
} else super.onDisplayPreferenceDialog(preference);
}
}
| 934 | Java | .java | ZeeRooo/MaterialFBook | 139 | 43 | 34 | 2016-09-12T22:22:02Z | 2021-07-18T16:20:04Z |
DatabaseHelper.java | /FileExtraction/Java_unseen/ZeeRooo_MaterialFBook/app/src/main/java/me/zeeroooo/materialfb/misc/DatabaseHelper.java | package me.zeeroooo.materialfb.misc;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/*
* Created by https://github.com/mitchtabian. Thank you :)
* Adapted by me.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "MFBBookmarks.db";
private static final String TABLE_NAME = "mfb_table";
private static final String COL1 = "TITLE";
private static final String COL2 = "URL";
private static final String COL3 = "BL";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, TITLE TEXT, URL TEXT, BL TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean addData(String title, String url, String blackword) {
final ContentValues contentValues = new ContentValues();
if (title != null && url != null) {
contentValues.put(COL1, title);
contentValues.put(COL2, url);
} else
contentValues.put(COL3, blackword);
long result = getWritableDatabase().insertWithOnConflict(TABLE_NAME, null, contentValues, SQLiteDatabase.CONFLICT_IGNORE);
return result != -1;
}
public void remove(String title, String url, String s) {
final SQLiteDatabase db = this.getWritableDatabase();
String query;
if (s == null)
query = "DELETE FROM " + TABLE_NAME + " WHERE " + COL1 + " = '" + title + "'" + " AND " + COL2 + " = '" + url + "'";
else
query = "DELETE FROM " + TABLE_NAME + " WHERE " + COL3 + " = '" + s + "'";
db.execSQL(query);
}
} | 2,014 | Java | .java | ZeeRooo/MaterialFBook | 139 | 43 | 34 | 2016-09-12T22:22:02Z | 2021-07-18T16:20:04Z |
ModelBookmarks.java | /FileExtraction/Java_unseen/ZeeRooo_MaterialFBook/app/src/main/java/me/zeeroooo/materialfb/misc/ModelBookmarks.java | package me.zeeroooo.materialfb.misc;
public class ModelBookmarks {
private String url, title;
public ModelBookmarks(String title, String url) {
this.url = url;
this.title = title;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
| 474 | Java | .java | ZeeRooo/MaterialFBook | 139 | 43 | 34 | 2016-09-12T22:22:02Z | 2021-07-18T16:20:04Z |
UserInfo.java | /FileExtraction/Java_unseen/ZeeRooo_MaterialFBook/app/src/main/java/me/zeeroooo/materialfb/misc/UserInfo.java | package me.zeeroooo.materialfb.misc;
import android.app.Activity;
import android.os.AsyncTask;
import android.webkit.CookieManager;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import me.zeeroooo.materialfb.R;
import me.zeeroooo.materialfb.webview.Helpers;
public class UserInfo extends AsyncTask<Activity, Void, Activity> {
private String name, cover;
@Override
protected Activity doInBackground(Activity[] activities) {
try {
if (!activities[0].isDestroyed()) {
final Element e = Jsoup.connect("https://mbasic.facebook.com/me").cookie(("https://m.facebook.com"), CookieManager.getInstance().getCookie(("https://m.facebook.com"))).timeout(300000).get().body();
if (name == null)
name = e.getElementsByClass("profpic img").attr("alt");
if (cover == null)
cover = Helpers.decodeImg(e.selectFirst("div#profile_cover_photo_container > a > img").attr("src"));
}
} catch (Exception e) {
e.printStackTrace();
}
return activities[0];
}
@Override
protected void onPostExecute(Activity activity) {
if (!activity.isDestroyed())
try {
if (name != null && activity.findViewById(R.id.profile_name) != null)
((TextView) activity.findViewById(R.id.profile_name)).setText(name);
if (cover != null && activity.findViewById(R.id.cover) != null)
Glide.with(activity)
.load(cover)
.apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL))
.into((ImageView) activity.findViewById(R.id.cover));
if (Helpers.getCookie() != null && activity.findViewById(R.id.profile_picture) != null)
Glide.with(activity)
.load("https://graph.facebook.com/" + Helpers.getCookie() + "/picture?type=large")
.apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL).circleCrop())
.into((ImageView) activity.findViewById(R.id.profile_picture));
} catch (Exception e) {
e.printStackTrace();
}
}
} | 2,517 | Java | .java | ZeeRooo/MaterialFBook | 139 | 43 | 34 | 2016-09-12T22:22:02Z | 2021-07-18T16:20:04Z |
NotificationsService.java | /FileExtraction/Java_unseen/ZeeRooo_MaterialFBook/app/src/main/java/me/zeeroooo/materialfb/notifications/NotificationsService.java | package me.zeeroooo.materialfb.notifications;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.webkit.CookieManager;
import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import androidx.core.app.TaskStackBuilder;
import androidx.preference.PreferenceManager;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import java.util.ArrayList;
import java.util.List;
import me.zeeroooo.materialfb.MFB;
import me.zeeroooo.materialfb.R;
import me.zeeroooo.materialfb.activities.MainActivity;
import me.zeeroooo.materialfb.misc.DatabaseHelper;
import me.zeeroooo.materialfb.webview.Helpers;
public class NotificationsService extends Worker {
private SharedPreferences mPreferences;
private boolean msg_notAWhiteList = false, notif_notAWhiteList = false;
private String baseURL, channelId;
private List<String> blist;
private NotificationManager mNotificationManager;
private NotificationCompat.Builder mBuilder;
public NotificationsService(Context context, WorkerParameters workerParameters) {
super(context, workerParameters);
}
private void URLs() {
if (!mPreferences.getBoolean("save_data", false))
baseURL = "https://m.facebook.com/";
else
baseURL = "https://mbasic.facebook.com/";
}
@NonNull
@Override
public Result doWork() {
final DatabaseHelper db = new DatabaseHelper(getApplicationContext());
final Cursor cursor = db.getReadableDatabase().rawQuery("SELECT BL FROM mfb_table", null);
mPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
URLs();
blist = new ArrayList<>();
mNotificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(getApplicationContext(), channelId);
try {
while (cursor != null && cursor.moveToNext())
if (cursor.getString(0) != null)
blist.add(cursor.getString(0));
if (mPreferences.getBoolean("facebook_messages", false))
SyncMessages();
if (mPreferences.getBoolean("facebook_notifications", false))
SyncNotifications();
if (!cursor.isClosed()) {
db.close();
cursor.close();
}
} catch (Exception e) {
e.printStackTrace();
return Worker.Result.failure();
}
return Worker.Result.success();
}
// Sync the notifications
private void SyncNotifications() throws Exception {
final Document doc = Jsoup.connect("https://m.facebook.com/notifications.php").cookie(("https://m.facebook.com"), CookieManager.getInstance().getCookie(("https://m.facebook.com"))).timeout(300000).get();
final Elements notifications = doc.select("div.aclb > div.touchable-notification > a.touchable");
String time, content, pictureNotif;
final StringBuilder stringBuilder = new StringBuilder();
int previousNotifLength;
for (byte a = 0; a < notifications.size(); a++) {
time = notifications.get(a).select("span.mfss.fcg").text();
content = notifications.get(a).select("div.c").text().replace(time, "");
previousNotifLength = stringBuilder.length();
if (!blist.isEmpty())
for (int position = 0; position < blist.size(); position++) {
if (content.toLowerCase().contains(blist.get(position).toLowerCase()))
notif_notAWhiteList = true;
}
if (!notif_notAWhiteList) {
pictureNotif = notifications.get(a).select("div.ib > i").attr("style");
stringBuilder.append(content.replace(time, ""));
if (!mPreferences.getString("last_notification_text", "").contains(stringBuilder.substring(previousNotifLength)))
notifier(stringBuilder.substring(previousNotifLength), getApplicationContext().getString(R.string.app_name), baseURL + "notifications.php", pictureNotif.split("('*')")[1], (int) System.currentTimeMillis(), false);
}
}
mPreferences.edit().putString("last_notification_text", stringBuilder.toString()).apply();
}
private void SyncMessages() throws Exception {
final Document doc = Jsoup.connect("https://mbasic.facebook.com/messages").cookie(("https://m.facebook.com"), CookieManager.getInstance().getCookie(("https://m.facebook.com"))).timeout(300000).get();
final Elements results = doc.getElementsByClass("bo bp bq br bs bt bu bv bw");
if (results != null) {
String name, pictureMsg;
final StringBuilder stringBuilder = new StringBuilder();
int previousMsgLength;
for (byte a = 0; a < results.size(); a++) {
previousMsgLength = stringBuilder.length();
stringBuilder.append(results.get(a).selectFirst("tr > td > header h3 > span").text());
if (!blist.isEmpty())
for (int position = 0; position < blist.size(); position++) {
if (stringBuilder.toString().toLowerCase().contains(blist.get(position).toLowerCase()))
msg_notAWhiteList = true;
}
if (!msg_notAWhiteList) {
name = results.get(a).selectFirst("tr > td > header h3 > a").text();
pictureMsg = "https://graph.facebook.com/" + results.get(a).select("tr > td > header h3 > a").attr("href").split("cid.c.")[1].split("&")[0].replace(Helpers.getCookie(), "").replace("%3A", "") + "/picture?type=large";
if (!mPreferences.getString("last_message", "").contains(stringBuilder.substring(previousMsgLength)))
notifier(stringBuilder.substring(previousMsgLength), name, baseURL + "messages", pictureMsg, (int) System.currentTimeMillis(), true);
}
}
mPreferences.edit().putString("last_message", stringBuilder.toString()).apply();
}
}
// create a notification and display it
private void notifier(final String content, final String title, final String url, final String image_url, int id, boolean isMessage) throws Exception {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (isMessage)
channelId = "me.zeeroooo.materialfb.notif.messages";
else
channelId = "me.zeeroooo.materialfb.notif.facebook";
} else
channelId = "me.zeeroooo.materialfb.notif";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// create all channels at once so users can see/configure them all with the first notification
if (mNotificationManager.getNotificationChannel("me.zeeroooo.materialfb.notif.messages") == null) {
createNotificationChannel(channelId, getApplicationContext().getString(R.string.facebook_message), "vibrate_double_msg");
createNotificationChannel(channelId, getApplicationContext().getString(R.string.facebook_notifications), "vibrate_double_notif");
}
} else {
String ringtoneKey, vibrateKey, vibrateDoubleKey, ledKey;
if (isMessage) {
ringtoneKey = "ringtone_msg";
vibrateKey = "vibrate_msg";
vibrateDoubleKey = "vibrate_double_msg";
ledKey = "led_msj";
} else {
ringtoneKey = "ringtone";
vibrateDoubleKey = "vibrate_double_notif";
vibrateKey = "vibrate_notif";
ledKey = "led_notif";
}
if (mPreferences.getBoolean(vibrateKey, false)) {
mBuilder.setVibrate(new long[]{500, 500});
if (mPreferences.getBoolean(vibrateDoubleKey, false))
mBuilder.setVibrate(new long[]{500, 500, 500, 500});
}
if (mPreferences.getBoolean(ledKey, false))
mBuilder.setLights(Color.BLUE, 1000, 1000);
mBuilder.setSound(Uri.parse(mPreferences.getString(ringtoneKey, "content://settings/system/notification_sound")));
mBuilder.setPriority(Notification.PRIORITY_HIGH);
}
mBuilder
.setChannelId(channelId)
.setStyle(new NotificationCompat.BigTextStyle().bigText(content))
.setColor(MFB.colorPrimary)
.setContentTitle(title)
.setContentText(content)
.setWhen(System.currentTimeMillis())
.setLargeIcon(Glide.with(getApplicationContext()).asBitmap().load(Helpers.decodeImg(image_url)).apply(RequestOptions.circleCropTransform()).into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL).get())
.setSmallIcon(R.drawable.ic_material)
.setAutoCancel(true);
// priority for Heads-up
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
mBuilder.setCategory(Notification.CATEGORY_MESSAGE);
final Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("notifUrl", url);
final TaskStackBuilder stackBuilder = TaskStackBuilder.create(getApplicationContext());
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(intent);
final PendingIntent resultPendingIntent = PendingIntent.getActivity(getApplicationContext(), id, intent, 0);
mBuilder.setContentIntent(resultPendingIntent);
if (mNotificationManager != null)
mNotificationManager.notify(id, mBuilder.build());
}
@TargetApi(26)
private void createNotificationChannel(String id, String name, String vibrateDouble) {
final NotificationChannel notificationChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setShowBadge(true);
notificationChannel.enableVibration(true);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.BLUE);
if (mPreferences.getBoolean(vibrateDouble, false))
notificationChannel.setVibrationPattern(new long[]{500, 500, 500, 500});
mNotificationManager.createNotificationChannel(notificationChannel);
}
/* public static void clearbyId(Context c, int id) {
NotificationManager mNotificationManager = (NotificationManager) c.getSystemService(Context.NOTIFICATION_SERVICE);
if (mNotificationManager != null)
mNotificationManager.cancel(id);
}*/
}
| 11,360 | Java | .java | ZeeRooo/MaterialFBook | 139 | 43 | 34 | 2016-09-12T22:22:02Z | 2021-07-18T16:20:04Z |
ExampleInstrumentedTest.java | /FileExtraction/Java_unseen/ZeeRooo_MaterialFBook/app/src/androidTest/java/me/zeeroooo/materialfb/ExampleInstrumentedTest.java | package me.zeeroooo.materialfb;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("me.zeeroooo.materialfb", appContext.getPackageName());
}
}
| 743 | Java | .java | ZeeRooo/MaterialFBook | 139 | 43 | 34 | 2016-09-12T22:22:02Z | 2021-07-18T16:20:04Z |
SWTResourceManager.java | /FileExtraction/Java_unseen/xuhyacinth_MusicPlayer/src/org/eclipse/wb/swt/SWTResourceManager.java | /*******************************************************************************
* Copyright (c) 2011 Google, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Google, Inc. - initial API and implementation
*******************************************************************************/
package org.eclipse.wb.swt;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.widgets.Display;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
/**
* Utility class for managing OS resources associated with SWT controls such as colors, fonts, images, etc.
* <p>
* !!! IMPORTANT !!! Application code must explicitly invoke the <code>dispose()</code> method to release the
* operating system resources managed by cached objects when those objects and OS resources are no longer
* needed (e.g. on application shutdown)
* <p>
* This class may be freely distributed as part of any application or plugin.
* <p>
*
* @author scheglov_ke
* @author Dan Rubel
*/
public class SWTResourceManager {
/**
* Style constant for placing decorator image in top left corner of base image.
*/
public static final int TOP_LEFT = 1;
/**
* Style constant for placing decorator image in top right corner of base image.
*/
public static final int TOP_RIGHT = 2;
/**
* Style constant for placing decorator image in bottom left corner of base image.
*/
public static final int BOTTOM_LEFT = 3;
/**
* Style constant for placing decorator image in bottom right corner of base image.
*/
public static final int BOTTOM_RIGHT = 4;
/**
* Internal value.
*/
protected static final int LAST_CORNER_KEY = 5;
////////////////////////////////////////////////////////////////////////////
//
// Image
//
////////////////////////////////////////////////////////////////////////////
private static final int MISSING_IMAGE_SIZE = 10;
////////////////////////////////////////////////////////////////////////////
//
// Color
//
////////////////////////////////////////////////////////////////////////////
private static Map<RGB, Color> m_colorMap = new HashMap<RGB, Color>();
/**
* Maps image paths to images.
*/
private static Map<String, Image> m_imageMap = new HashMap<String, Image>();
/**
* Maps images to decorated images.
*/
@SuppressWarnings("unchecked")
private static Map<Image, Map<Image, Image>>[] m_decoratedImageMap = new Map[LAST_CORNER_KEY];
/**
* Maps font names to fonts.
*/
private static Map<String, Font> m_fontMap = new HashMap<String, Font>();
/**
* Maps fonts to their bold versions.
*/
private static Map<Font, Font> m_fontToBoldFontMap = new HashMap<Font, Font>();
/**
* Maps IDs to cursors.
*/
private static Map<Integer, Cursor> m_idToCursorMap = new HashMap<Integer, Cursor>();
/**
* Returns the system {@link Color} matching the specific ID.
*
* @param systemColorID the ID value for the color
* @return the system {@link Color} matching the specific ID
*/
public static Color getColor(int systemColorID) {
Display display = Display.getCurrent();
return display.getSystemColor(systemColorID);
}
/**
* Returns a {@link Color} given its red, green and blue component values.
*
* @param r the red component of the color
* @param g the green component of the color
* @param b the blue component of the color
* @return the {@link Color} matching the given red, green and blue component values
*/
public static Color getColor(int r, int g, int b) {
return getColor(new RGB(r, g, b));
}
/**
* Returns a {@link Color} given its RGB value.
*
* @param rgb the {@link RGB} value of the color
* @return the {@link Color} matching the RGB value
*/
public static Color getColor(RGB rgb) {
Color color = m_colorMap.get(rgb);
if (color == null) {
Display display = Display.getCurrent();
color = new Color(display, rgb);
m_colorMap.put(rgb, color);
}
return color;
}
/**
* Dispose of all the cached {@link Color}'s.
*/
public static void disposeColors() {
for (Color color : m_colorMap.values()) {
color.dispose();
}
m_colorMap.clear();
}
/**
* Returns an {@link Image} encoded by the specified {@link InputStream}.
*
* @param stream the {@link InputStream} encoding the image data
* @return the {@link Image} encoded by the specified input stream
*/
protected static Image getImage(InputStream stream) throws IOException {
try {
Display display = Display.getCurrent();
ImageData data = new ImageData(stream);
if (data.transparentPixel > 0) {
return new Image(display, data, data.getTransparencyMask());
}
return new Image(display, data);
} finally {
stream.close();
}
}
/**
* Returns an {@link Image} stored in the file at the specified path.
*
* @param path the path to the image file
* @return the {@link Image} stored in the file at the specified path
*/
public static Image getImage(String path) {
Image image = m_imageMap.get(path);
if (image == null) {
try {
image = getImage(new FileInputStream(path));
m_imageMap.put(path, image);
} catch (Exception e) {
image = getMissingImage();
m_imageMap.put(path, image);
}
}
return image;
}
/**
* Returns an {@link Image} stored in the file at the specified path relative to the specified class.
*
* @param clazz the {@link Class} relative to which to find the image
* @param path the path to the image file, if starts with <code>'/'</code>
* @return the {@link Image} stored in the file at the specified path
*/
public static Image getImage(Class<?> clazz, String path) {
String key = clazz.getName() + '|' + path;
Image image = m_imageMap.get(key);
if (image == null) {
try {
image = getImage(clazz.getResourceAsStream(path));
m_imageMap.put(key, image);
} catch (Exception e) {
image = getMissingImage();
m_imageMap.put(key, image);
}
}
return image;
}
/**
* @return the small {@link Image} that can be used as placeholder for missing image.
*/
private static Image getMissingImage() {
Image image = new Image(Display.getCurrent(), MISSING_IMAGE_SIZE, MISSING_IMAGE_SIZE);
//
GC gc = new GC(image);
gc.setBackground(getColor(SWT.COLOR_RED));
gc.fillRectangle(0, 0, MISSING_IMAGE_SIZE, MISSING_IMAGE_SIZE);
gc.dispose();
//
return image;
}
////////////////////////////////////////////////////////////////////////////
//
// Font
//
////////////////////////////////////////////////////////////////////////////
/**
* Returns an {@link Image} composed of a base image decorated by another image.
*
* @param baseImage the base {@link Image} that should be decorated
* @param decorator the {@link Image} to decorate the base image
* @return {@link Image} The resulting decorated image
*/
public static Image decorateImage(Image baseImage, Image decorator) {
return decorateImage(baseImage, decorator, BOTTOM_RIGHT);
}
/**
* Returns an {@link Image} composed of a base image decorated by another image.
*
* @param baseImage the base {@link Image} that should be decorated
* @param decorator the {@link Image} to decorate the base image
* @param corner the corner to place decorator image
* @return the resulting decorated {@link Image}
*/
public static Image decorateImage(final Image baseImage, final Image decorator, final int corner) {
if (corner <= 0 || corner >= LAST_CORNER_KEY) {
throw new IllegalArgumentException("Wrong decorate corner");
}
Map<Image, Map<Image, Image>> cornerDecoratedImageMap = m_decoratedImageMap[corner];
if (cornerDecoratedImageMap == null) {
cornerDecoratedImageMap = new HashMap<Image, Map<Image, Image>>();
m_decoratedImageMap[corner] = cornerDecoratedImageMap;
}
Map<Image, Image> decoratedMap = cornerDecoratedImageMap.computeIfAbsent(baseImage, k -> new HashMap<Image, Image>());
//
Image result = decoratedMap.get(decorator);
if (result == null) {
Rectangle bib = baseImage.getBounds();
Rectangle dib = decorator.getBounds();
//
result = new Image(Display.getCurrent(), bib.width, bib.height);
//
GC gc = new GC(result);
gc.drawImage(baseImage, 0, 0);
if (corner == TOP_LEFT) {
gc.drawImage(decorator, 0, 0);
} else if (corner == TOP_RIGHT) {
gc.drawImage(decorator, bib.width - dib.width, 0);
} else if (corner == BOTTOM_LEFT) {
gc.drawImage(decorator, 0, bib.height - dib.height);
} else if (corner == BOTTOM_RIGHT) {
gc.drawImage(decorator, bib.width - dib.width, bib.height - dib.height);
}
gc.dispose();
//
decoratedMap.put(decorator, result);
}
return result;
}
/**
* Dispose all of the cached {@link Image}'s.
*/
public static void disposeImages() {
// dispose loaded images
{
for (Image image : m_imageMap.values()) {
image.dispose();
}
m_imageMap.clear();
}
// dispose decorated images
for (int i = 0; i < m_decoratedImageMap.length; i++) {
Map<Image, Map<Image, Image>> cornerDecoratedImageMap = m_decoratedImageMap[i];
if (cornerDecoratedImageMap != null) {
for (Map<Image, Image> decoratedMap : cornerDecoratedImageMap.values()) {
for (Image image : decoratedMap.values()) {
image.dispose();
}
decoratedMap.clear();
}
cornerDecoratedImageMap.clear();
}
}
}
/**
* Returns a {@link Font} based on its name, height and style.
*
* @param name the name of the font
* @param height the height of the font
* @param style the style of the font
* @return {@link Font} The font matching the name, height and style
*/
public static Font getFont(String name, int height, int style) {
return getFont(name, height, style, false, false);
}
/**
* Returns a {@link Font} based on its name, height and style. Windows-specific strikeout and underline
* flags are also supported.
*
* @param name the name of the font
* @param size the size of the font
* @param style the style of the font
* @param strikeout the strikeout flag (warning: Windows only)
* @param underline the underline flag (warning: Windows only)
* @return {@link Font} The font matching the name, height, style, strikeout and underline
*/
public static Font getFont(String name, int size, int style, boolean strikeout, boolean underline) {
String fontName = name + '|' + size + '|' + style + '|' + strikeout + '|' + underline;
Font font = m_fontMap.get(fontName);
if (font == null) {
FontData fontData = new FontData(name, size, style);
if (strikeout || underline) {
try {
Class<?> logFontClass = Class.forName("org.eclipse.swt.internal.win32.LOGFONT"); //$NON-NLS-1$
Object logFont = FontData.class.getField("data").get(fontData); //$NON-NLS-1$
if (logFont != null && logFontClass != null) {
if (strikeout) {
logFontClass.getField("lfStrikeOut").set(logFont, Byte.valueOf((byte) 1)); //$NON-NLS-1$
}
if (underline) {
logFontClass.getField("lfUnderline").set(logFont, Byte.valueOf((byte) 1)); //$NON-NLS-1$
}
}
} catch (Throwable e) {
System.err.println("Unable to set underline or strikeout" + " (probably on a non-Windows platform). " + e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
font = new Font(Display.getCurrent(), fontData);
m_fontMap.put(fontName, font);
}
return font;
}
/**
* Returns a bold version of the given {@link Font}.
*
* @param baseFont the {@link Font} for which a bold version is desired
* @return the bold version of the given {@link Font}
*/
public static Font getBoldFont(Font baseFont) {
Font font = m_fontToBoldFontMap.get(baseFont);
if (font == null) {
FontData[] fontDatas = baseFont.getFontData();
FontData data = fontDatas[0];
font = new Font(Display.getCurrent(), data.getName(), data.getHeight(), SWT.BOLD);
m_fontToBoldFontMap.put(baseFont, font);
}
return font;
}
////////////////////////////////////////////////////////////////////////////
//
// Cursor
//
////////////////////////////////////////////////////////////////////////////
/**
* Dispose all of the cached {@link Font}'s.
*/
public static void disposeFonts() {
// clear fonts
for (Font font : m_fontMap.values()) {
font.dispose();
}
m_fontMap.clear();
// clear bold fonts
for (Font font : m_fontToBoldFontMap.values()) {
font.dispose();
}
m_fontToBoldFontMap.clear();
}
/**
* Returns the system cursor matching the specific ID.
*
* @param id int The ID value for the cursor
* @return Cursor The system cursor matching the specific ID
*/
public static Cursor getCursor(int id) {
Integer key = Integer.valueOf(id);
Cursor cursor = m_idToCursorMap.get(key);
if (cursor == null) {
cursor = new Cursor(Display.getDefault(), id);
m_idToCursorMap.put(key, cursor);
}
return cursor;
}
/**
* Dispose all of the cached cursors.
*/
public static void disposeCursors() {
for (Cursor cursor : m_idToCursorMap.values()) {
cursor.dispose();
}
m_idToCursorMap.clear();
}
////////////////////////////////////////////////////////////////////////////
//
// General
//
////////////////////////////////////////////////////////////////////////////
/**
* Dispose of cached objects and their underlying OS resources. This should only be called when the cached
* objects are no longer needed (e.g. on application shutdown).
*/
public static void dispose() {
disposeColors();
disposeImages();
disposeFonts();
disposeCursors();
}
} | 13,786 | Java | .java | xuhyacinth/MusicPlayer | 9 | 0 | 0 | 2020-12-13T04:23:25Z | 2022-03-15T03:58:12Z |
LoadLocalLyric.java | /FileExtraction/Java_unseen/xuhyacinth_MusicPlayer/src/com/xu/music/player/lyric/LoadLocalLyric.java | package com.xu.music.player.lyric;
import com.xu.music.player.system.Constant;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Java MusicPlayer 加载本地歌词
*
* @Author: hyacinth
* @ClassName: LoadLyric
* @Description: TODO
* @Date: 2019年12月26日 下午8:00:46
* @Copyright: hyacinth
*/
public class LoadLocalLyric {
public static void main(String[] args) throws IOException {
LoadLocalLyric lyric = new LoadLocalLyric();
lyric.lyric("F:\\KuGou\\丸子呦 - 广寒宫.lrc");
for (String s : Constant.PLAYING_SONG_LYRIC) {
System.out.println(s);
}
}
/**
* 获取本地歌曲歌词
*/
public List<String> lyric(String path) {
Constant.PLAYING_SONG_LYRIC.clear();
File file = new File(path);
if (file.exists()) {
InputStreamReader fReader = null;
BufferedReader bReader = null;
try (FileInputStream stream = new FileInputStream(file)) {
fReader = new InputStreamReader(stream, StandardCharsets.UTF_8);
bReader = new BufferedReader(fReader);
String txt;
String reg = "\\[(\\d{2}:\\d{2}\\.\\d{2})\\]|\\[\\d{2}:\\d{2}\\]";
while ((txt = bReader.readLine()) != null) {
if (txt.contains("[ti:")) { // 歌曲信息
Constant.PLAYING_SONG_LYRIC.add("歌曲信息: " + Constant.MUSIC_PLAYER_SYSTEM_SPLIT + txt.substring(txt.lastIndexOf(":") + 1, txt.length() - 1) + "");
} else if (txt.contains("[ar:")) {// 歌手信息
Constant.PLAYING_SONG_LYRIC.add("歌手信息: " + Constant.MUSIC_PLAYER_SYSTEM_SPLIT + txt.substring(txt.lastIndexOf(":") + 1, txt.length() - 1) + " ");
} else if (txt.contains("[al:")) {// 专辑信息
Constant.PLAYING_SONG_LYRIC.add("专辑信息: " + Constant.MUSIC_PLAYER_SYSTEM_SPLIT + txt.substring(txt.lastIndexOf(":") + 1, txt.length() - 1) + " ");
} else if (txt.contains("[wl:")) {// 歌词作家
Constant.PLAYING_SONG_LYRIC.add("歌词作家: " + Constant.MUSIC_PLAYER_SYSTEM_SPLIT + txt.substring(txt.lastIndexOf(":") + 1, txt.length() - 1) + " ");
} else if (txt.contains("[wm:")) {// 歌曲作家
Constant.PLAYING_SONG_LYRIC.add("歌曲作家: " + Constant.MUSIC_PLAYER_SYSTEM_SPLIT + txt.substring(txt.lastIndexOf(":") + 1, txt.length() - 1) + " ");
} else if (txt.contains("[al:")) {// 歌词制作
Constant.PLAYING_SONG_LYRIC.add("歌词制作: " + Constant.MUSIC_PLAYER_SYSTEM_SPLIT + txt.substring(txt.lastIndexOf(":") + 1, txt.length() - 1) + " ");
} else {
Pattern pattern = Pattern.compile(reg);
Matcher matcher = pattern.matcher(txt);
while (matcher.find()) {
Constant.PLAYING_SONG_LYRIC.add(matcher.group(0).substring(1, matcher.group(0).lastIndexOf("]")).trim() + Constant.MUSIC_PLAYER_SYSTEM_SPLIT + txt.substring(txt.lastIndexOf("]") + 1).trim() + " ");
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fReader != null) {
try {
fReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bReader != null) {
try {
bReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return Constant.PLAYING_SONG_LYRIC;
}
@SuppressWarnings("unused")
private List<String> sort_lyric(List<String> lyric) {
for (int i = 0; i < lyric.size(); i++) {
if (Pattern.matches("^\\d+$", lyric.get(i).substring(0, 2))) {
if (Pattern.matches("^\\d{2}:\\d{2}\\.\\d{1}$", lyric.get(i).substring(0, 7))) {
for (int j = 0; j < lyric.size(); j++) {
if (Pattern.matches("^\\d+$", lyric.get(j).substring(0, 2))) {
if (Double.parseDouble(lyric.get(i).substring(0, 2)) < Double.parseDouble(lyric.get(j).substring(0, 2))) {
String temp = lyric.get(i);
lyric.set(i, lyric.get(j));
lyric.set(j, temp);
}
if (Double.parseDouble(lyric.get(i).substring(0, 2)) == Double.parseDouble(lyric.get(j).substring(0, 2)) && Double.parseDouble(lyric.get(i).substring(3, 8)) < Double.parseDouble(lyric.get(j).substring(3, 8))) {
String temp = lyric.get(i);
lyric.set(i, lyric.get(j));
lyric.set(j, temp);
}
}
}
} else if (Pattern.matches("^\\d{2}:\\d{2}$", lyric.get(i).substring(0, 5))) {
for (int j = 0; j < lyric.size(); j++) {
if (Pattern.matches("^\\d+$", lyric.get(j).substring(0, 2))) {
if (Integer.parseInt(lyric.get(i).substring(0, 2)) < Integer.parseInt(lyric.get(j).substring(0, 2))) {
String temp = lyric.get(i);
lyric.set(i, lyric.get(j));
lyric.set(j, temp);
}
if (Integer.parseInt(lyric.get(i).substring(0, 2)) == Integer.parseInt(lyric.get(j).substring(0, 2)) && Integer.parseInt(lyric.get(i).substring(3, 5)) < Double.parseDouble(lyric.get(j).substring(3, 5))) {
String temp = lyric.get(i);
lyric.set(i, lyric.get(j));
lyric.set(j, temp);
}
}
}
}
}
}
return lyric;
}
}
| 6,448 | Java | .java | xuhyacinth/MusicPlayer | 9 | 0 | 0 | 2020-12-13T04:23:25Z | 2022-03-15T03:58:12Z |
LyricyNotify.java | /FileExtraction/Java_unseen/xuhyacinth_MusicPlayer/src/com/xu/music/player/lyric/LyricyNotify.java | package com.xu.music.player.lyric;
/**
* Java MusicPlayer 歌词线程通知
*
* @Author: hyacinth
* @ClassName: LyricyNotify
* @Description: TODO
* @Date: 2019年12月26日 下午8:01:37
* @Copyright: hyacinth
*/
public interface LyricyNotify {
/**
* Java MusicPlayer 歌词线程通知
* @param lrc
* @param pro
*/
void lyric(double lrc, double pro);
}
| 394 | Java | .java | xuhyacinth/MusicPlayer | 9 | 0 | 0 | 2020-12-13T04:23:25Z | 2022-03-15T03:58:12Z |
MusicPlayerTest.java | /FileExtraction/Java_unseen/xuhyacinth_MusicPlayer/src/com/xu/music/player/test/MusicPlayerTest.java | package com.xu.music.player.test;
import com.xu.music.player.player.Player;
import com.xu.music.player.player.XMusic;
import com.xu.music.player.tray.MusicPlayerTray;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.*;
import org.eclipse.wb.swt.SWTResourceManager;
import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
@SuppressWarnings(value = "all")
public class MusicPlayerTest {
private static int totalPlayTime;
protected Shell shell;
private Display display;
private Player player = XMusic.player();
private Button button;
private Table table;
private Tray tray;
private String playPath;
private Text text;
private Thread playProgress;
private ProgressBar progressBar;
private Text text_1;
private int clickX, clickY;
private Boolean click = false;
private Label label_5;
private int judeg = 0;
private StringBuilder BufferPlayList;
private Text text_2;
private Text text_3;
private int lyricTimes = 0;
private String[] lyrics = new String[200];
private boolean haslyric = false;
private Table table_1;
private String[] playlist;
private GC gc;
/**
* Launch the application.
*
* @param args
*/
public static void main(String[] args) {
try {
MusicPlayerTest window = new MusicPlayerTest();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Open the window.
*/
public void open() {
display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
* Create contents of the window.
*/
protected void createContents() {
shell = new Shell(SWT.NONE);
shell.setImage(SWTResourceManager.getImage(MusicPlayerTest.class, "/com/xu/musicplayer/image/music.png"));
shell.setSize(new Point(1000, 645));
shell.setSize(889, 485);
shell.setText("音乐");
shell.setLocation((display.getClientArea().width - shell.getSize().x) / 2,
(display.getClientArea().height - shell.getSize().y) / 2);
shell.setLayout(new FillLayout(SWT.HORIZONTAL));
// 托盘引入
tray = display.getSystemTray();
MusicPlayerTray trayutil = new MusicPlayerTray(shell, tray);
trayutil.tray();
Composite composite = new Composite(shell, SWT.NO_RADIO_GROUP);
composite.setLayout(new FormLayout());
button = new Button(composite, SWT.NONE);
button.setImage(SWTResourceManager.getImage(MusicPlayerTest.class, "/com/xu/musicplayer/image/addMusic.png"));
FormData fd_button = new FormData();
fd_button.right = new FormAttachment(100, -803);
fd_button.left = new FormAttachment(0);
button.setLayoutData(fd_button);
button.setText(" 添 加 ");
FormData fd_composite_2 = new FormData();
fd_composite_2.left = new FormAttachment(0, 105);
fd_composite_2.bottom = new FormAttachment(100, -10);
fd_composite_2.top = new FormAttachment(0, 382);
fd_composite_2.right = new FormAttachment(100, -123);
table = new Table(composite, SWT.FULL_SELECTION);
FormData fd_table = new FormData();
fd_table.top = new FormAttachment(button, 6);
fd_table.left = new FormAttachment(0);
fd_table.right = new FormAttachment(100, -689);
table.setLayoutData(fd_table);
table.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_LIGHT_SHADOW));
table.setHeaderVisible(true);
table.setLinesVisible(true);
TableColumn tableColumn_2 = new TableColumn(table, SWT.NONE);
tableColumn_2.setWidth(37);
tableColumn_2.setText("编号");
TableColumn tableColumn_1 = new TableColumn(table, SWT.NONE);
tableColumn_1.setWidth(244);
tableColumn_1.setText("默 认 列 表");
Composite composite_1 = new Composite(composite, SWT.NONE);
fd_button.top = new FormAttachment(composite_1, 6);
composite_1.setBackgroundMode(SWT.INHERIT_DEFAULT);
composite_1.setBackground(SWTResourceManager.getColor(SWT.COLOR_CYAN));
FormData fd_composite_1 = new FormData();
fd_composite_1.top = new FormAttachment(0);
fd_composite_1.left = new FormAttachment(0);
fd_composite_1.right = new FormAttachment(0, 887);
fd_composite_1.bottom = new FormAttachment(0, 56);
composite_1.setLayoutData(fd_composite_1);
Label label = new Label(composite_1, SWT.NONE);
label.setImage(SWTResourceManager.getImage(MusicPlayerTest.class, "/com/xu/musicplayer/image/hand.png"));
label.setBounds(0, 0, 56, 56);
gc = new GC(label);
gc.fillOval(0, 0, 56, 56);
gc.setBackground(SWTResourceManager.getColor(new RGB(11, 22, 22)));
gc.dispose();
final Label label_1 = new Label(composite_1, SWT.NONE);
label_1.setImage(SWTResourceManager.getImage(MusicPlayerTest.class, "/com/xu/musicplayer/image/minus_1.png"));
label_1.setBounds(817, 0, 32, 32);
final Label label_2 = new Label(composite_1, SWT.NONE);
label_2.setImage(SWTResourceManager.getImage(MusicPlayerTest.class, "/com/xu/musicplayer/image/delete_1.png"));
label_2.setBounds(855, 0, 32, 32);
Label lblNewLabel = new Label(composite_1, SWT.NONE);
lblNewLabel.setBounds(72, 20, 61, 17);
lblNewLabel.setText("月色深蓝");
Composite composite_3 = new Composite(composite, SWT.NONE);
fd_table.bottom = new FormAttachment(composite_3, -6);
composite_3.setBackgroundMode(SWT.INHERIT_DEFAULT);
composite_3.setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY));
FormData fd_composite_3 = new FormData();
fd_composite_3.top = new FormAttachment(0, 409);
fd_composite_3.bottom = new FormAttachment(100);
fd_composite_3.right = new FormAttachment(composite_1, 0, SWT.RIGHT);
text_2 = new Text(composite_1, SWT.NONE);
text_2.setForeground(SWTResourceManager.getColor(SWT.COLOR_CYAN));
text_2.setText("111");
text_2.setFont(SWTResourceManager.getFont("Microsoft YaHei UI", 16, SWT.NORMAL));
text_2.setBounds(281, 12, 336, 32);
Label label_6 = new Label(composite_1, SWT.NONE);
label_6.setImage(SWTResourceManager.getImage(MusicPlayerTest.class, "/com/xu/musicplayer/image/find.png"));
label_6.setBounds(640, 12, 32, 32);
fd_composite_3.left = new FormAttachment(0);
composite_3.setLayoutData(fd_composite_3);
Label label_3 = new Label(composite_3, SWT.NONE);
label_3.setImage(SWTResourceManager.getImage(MusicPlayerTest.class, "/com/xu/musicplayer/image/prev.png"));
label_3.setBounds(24, 27, 24, 24);
Composite composite_2 = new Composite(composite_3, SWT.NONE);
composite_2.setLocation(225, 48);
composite_2.setSize(452, 10);
composite_2.setLayout(new FillLayout(SWT.HORIZONTAL));
progressBar = new ProgressBar(composite_2, SWT.NONE);
progressBar.setBounds(0, 0, 655, 27);//设置进度条的位置
Label label_4 = new Label(composite_3, SWT.NONE);
label_4.setImage(SWTResourceManager.getImage(MusicPlayerTest.class, "/com/xu/musicplayer/image/next.png"));
label_4.setBounds(132, 27, 24, 24);
text_1 = new Text(composite_3, SWT.READ_ONLY);
text_1.setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY));
text_1.setBounds(225, 10, 287, 27);
text_1.setForeground(SWTResourceManager.getColor(SWT.COLOR_GREEN));
text_1.setFont(SWTResourceManager.getFont("Microsoft YaHei UI", 12, SWT.NORMAL));
text_1.setEnabled(false);
text = new Text(composite_3, SWT.READ_ONLY | SWT.CENTER);
text.setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY));
text.setBounds(541, 10, 136, 27);
text.setForeground(SWTResourceManager.getColor(SWT.COLOR_GREEN));
text.setFont(SWTResourceManager.getFont("Microsoft YaHei UI", 12, SWT.NORMAL));
text.setEnabled(false);
label_5 = new Label(composite_3, SWT.NONE);
label_5.setImage(SWTResourceManager.getImage(MusicPlayerTest.class, "/com/xu/musicplayer/image/begin.png"));
label_5.setBounds(79, 27, 24, 24);
Button button_1 = new Button(composite, SWT.NONE);
button_1.setText("扫 描");
button_1.setImage(SWTResourceManager.getImage(MusicPlayerTest.class, "/com/xu/musicplayer/image/search.png"));
FormData fd_button_1 = new FormData();
fd_button_1.left = new FormAttachment(table, -84);
fd_button_1.bottom = new FormAttachment(button, 0, SWT.BOTTOM);
fd_button_1.right = new FormAttachment(table, 0, SWT.RIGHT);
button_1.setLayoutData(fd_button_1);
text_3 = new Text(composite, SWT.READ_ONLY | SWT.CENTER);
text_3.setFont(SWTResourceManager.getFont("Microsoft YaHei UI", 16, SWT.NORMAL));
text_3.setForeground(SWTResourceManager.getColor(SWT.COLOR_RED));
FormData fd_text_3 = new FormData();
fd_text_3.right = new FormAttachment(table, 629, SWT.RIGHT);
fd_text_3.top = new FormAttachment(composite_1, 313);
fd_text_3.bottom = new FormAttachment(composite_3, -6);
fd_text_3.left = new FormAttachment(table, 6);
text_3.setLayoutData(fd_text_3);
table_1 = new Table(composite, SWT.FULL_SELECTION);
FormData fd_table_1 = new FormData();
fd_table_1.bottom = new FormAttachment(text_3, -6);
fd_table_1.right = new FormAttachment(text_3, 0, SWT.RIGHT);
fd_table_1.top = new FormAttachment(table, 0, SWT.TOP);
fd_table_1.left = new FormAttachment(table, 6);
table_1.setLayoutData(fd_table_1);
table_1.setHeaderVisible(true);
table_1.setLinesVisible(true);
TableColumn tableColumn = new TableColumn(table_1, SWT.NONE);
tableColumn.setWidth(621);
tableColumn.setText(" 歌词");
button_1.addMouseListener(new MouseAdapter() {
@Override
public void mouseUp(MouseEvent e) {
//new SearchMusic().open();//寻找播放文件的界面
}
});
playProgress = new Thread(new PlayProgress(display));
//playProgress.setDaemon(true);
getMusicPlayerFile();//读取本地播放文件
//选择菜单中的音乐
table.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
TableItem[] items = table.getSelection();
playPath = items[0].getText(1).trim();
String[] musicList = BufferPlayList.toString().split("<-->");
for (String lyric : musicList) {
if (lyric.substring(lyric.lastIndexOf("\\") + 1, lyric.lastIndexOf(".")).equals(playPath)) {
playPath = lyric;
}
}
updateList(playPath);
}
});
//导入本地播放文件
button.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
inputMusicPlayerFile();
}
});
//退出
label_2.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
label_2.setImage(SWTResourceManager.getImage(MusicPlayerTest.class, "/com/xu/musicplayer/image/delete_2.png"));
}
@Override
public void mouseUp(MouseEvent e) {
label_2.setImage(SWTResourceManager.getImage(MusicPlayerTest.class, "/com/xu/musicplayer/image/delete_1.png"));
tray.dispose();
distory();
}
});
label_2.addMouseTrackListener(new MouseTrackAdapter() {
@Override
public void mouseExit(MouseEvent e) {
label_2.setImage(SWTResourceManager.getImage(MusicPlayerTest.class, "/com/xu/musicplayer/image/delete_1.png"));
}
@Override
public void mouseHover(MouseEvent e) {
label_2.setImage(SWTResourceManager.getImage(MusicPlayerTest.class, "/com/xu/musicplayer/image/delete_2.png"));
label_2.setToolTipText("退出");
}
});
//缩小
label_1.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
label_1.setImage(SWTResourceManager.getImage(MusicPlayerTest.class, "/com/xu/musicplayer/image/minus_2.png"));
}
@Override
public void mouseUp(MouseEvent e) {
label_1.setImage(SWTResourceManager.getImage(MusicPlayerTest.class, "/com/xu/musicplayer/image/minus_1.png"));
shell.setMinimized(true);
}
});
label_1.addMouseTrackListener(new MouseTrackAdapter() {
@Override
public void mouseExit(MouseEvent e) {
label_1.setImage(SWTResourceManager.getImage(MusicPlayerTest.class, "/com/xu/musicplayer/image/minus_1.png"));
}
@Override
public void mouseHover(MouseEvent e) {
label_1.setImage(SWTResourceManager.getImage(MusicPlayerTest.class, "/com/xu/musicplayer/image/minus_2.png"));
label_1.setToolTipText("最小化");
}
});
progressBar.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
System.out.println(e.widget);
}
});
//界面移动
composite_1.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
click = true;
clickX = e.x;
clickY = e.y;
}
@Override
public void mouseUp(MouseEvent e) {
click = false;
}
});
composite_1.addMouseMoveListener(arg0 -> {//当鼠标按下的时候执行这条语句
if (click) {
shell.setLocation(shell.getLocation().x - clickX + arg0.x, shell.getLocation().y - clickY + arg0.y);
}
});
//播放按钮
label_5.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
}
@SuppressWarnings("deprecation")
@Override
public void mouseUp(MouseEvent e) {
judeg++;
if (judeg % 2 != 0) {//单击音乐开始
if (playPath == null || "".equals(playPath)) {
Toolkit toolkit = Toolkit.getDefaultToolkit();
toolkit.beep();
MessageDialog.openError(shell, "错误提示", "请选择播放文件");
} else {
label_5.setImage(SWTResourceManager.getImage(MusicPlayerTest.class, "/com/xu/musicplayer/image/stop.png"));
musicPlayerStart(playPath);
lyric(playPath);
}
} else {//单击音乐停止
label_5.setImage(SWTResourceManager.getImage(MusicPlayerTest.class, "/com/xu/musicplayer/image/begin.png"));
playProgress.stop();
progressBar.setSelection(0);
player.stop();
text.setText("");
}
if (judeg == 4) {
judeg = 0;
}
}
});
//上一曲
label_3.addMouseListener(new MouseAdapter() {
@Override
public void mouseUp(MouseEvent e) {
if (text_1.getText().trim() == null || "".equals(text_1.getText().trim())) {
String[] musicList = BufferPlayList.toString().split("<-->");
int playLists = new Random().nextInt(musicList.length) + 1;
if (!musicList[playLists].endsWith(".lrc")) {
playPath = musicList[playLists];
} else {
if (playLists == musicList.length) {
playPath = musicList[playLists - 1];
} else if (playLists == 0) {
playPath = musicList[playLists + 1];
} else {
playPath = musicList[playLists + 1];
}
}
label_5.setImage(SWTResourceManager.getImage(MusicPlayerTest.class, "/com/xu/musicplayer/image/stop.png"));
haslyric = false;
totalMethod(playPath.trim());
judeg = 1;
} else {
//结束现在所有
endAll();
String[] musicList = BufferPlayList.toString().split("<-->");
int playLists = new Random().nextInt(musicList.length) + 1;
if (!musicList[playLists].endsWith(".lrc")) {
playPath = musicList[playLists];
} else {
if (playLists == musicList.length) {
playPath = musicList[playLists - 1];
} else if (playLists == 0) {
playPath = musicList[playLists + 1];
} else {
playPath = musicList[playLists + 1];
}
}
label_5.setImage(SWTResourceManager.getImage(MusicPlayerTest.class, "/com/xu/musicplayer/image/stop.png"));
haslyric = false;
totalMethod(playPath.trim());
judeg = 1;
}
}
});
//下一曲
label_4.addMouseListener(new MouseAdapter() {
@Override
public void mouseUp(MouseEvent e) {
if (text_1.getText().trim() == null || "".equals(text_1.getText().trim())) {
int playLists = new Random().nextInt(playlist.length);
if (!playlist[playLists].endsWith(".lrc")) {
playPath = playlist[playLists];
} else {
if (playLists == playlist.length) {
playPath = playlist[playLists - 1];
} else if (playLists == 0) {
playPath = playlist[playLists + 1];
} else {
playPath = playlist[playLists + 1];
}
}
label_5.setImage(SWTResourceManager.getImage(MusicPlayerTest.class, "/com/xu/musicplayer/image/stop.png"));
haslyric = false;
totalMethod(playPath.trim());
judeg = 1;
} else {
//结束现在所有
endAll();
int playLists = new Random().nextInt(playlist.length);
if (!playlist[playLists].endsWith(".lrc")) {
playPath = playlist[playLists];
} else {
if (playLists == playlist.length) {
playPath = playlist[playLists - 1];
} else if (playLists == 0) {
playPath = playlist[playLists + 1];
} else {
playPath = playlist[playLists + 1];
}
}
label_5.setImage(SWTResourceManager.getImage(MusicPlayerTest.class, "/com/xu/musicplayer/image/stop.png"));
haslyric = false;
totalMethod(playPath.trim());
judeg = 1;
}
}
});
}
@SuppressWarnings("deprecation")
public void endAll() {
//结束现在所有
if ("RUNNABLE".equalsIgnoreCase(playProgress.getState().toString())) {//在运行
playProgress.stop();
}
try {
player.end();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
progressBar.setSelection(0);
}
/**
* 调用所需的方法
*
* @param playpath
*/
public void totalMethod(String playpath) {
musicPlayerStart(playPath.trim());//开始音乐
lyric(playPath.trim());//显示歌词
updateList(playPath.trim());//改变行的颜色
}
/**
* 显示歌词
*
* @param playPaths
*/
private void lyric(String playPaths) {
lyricTimes = 0;
TableItem tableItem = null;
if (playPaths.endsWith("wav") || playPaths.endsWith("mp3")) {//对传进来的歌曲进行截取
playPaths = playPaths.substring(playPaths.lastIndexOf("\\") + 1, playPaths.lastIndexOf(".")).trim();
}
for (String lyric : playlist) {//为歌词匹配路径
if (lyric.endsWith("lrc") || lyric.endsWith("LRC")) {
if (lyric.trim().substring(lyric.lastIndexOf("\\") + 1, lyric.lastIndexOf(".")).equals(playPaths)) {
playPaths = lyric;
haslyric = true;
break;
} else {
haslyric = false;
}
}
}
System.out.println("是否拥有歌词: " + haslyric + "\n歌词名: " + playPaths);
if (haslyric) {
String m;//分钟
String s;//秒钟
int index = 0;
try {
FileReader reader = new FileReader(new File(playPaths));
BufferedReader bufferedReader = new BufferedReader(reader);
String text;
while ((text = bufferedReader.readLine()) != null) {
String time = text.substring(1, text.lastIndexOf("]"));//歌曲时间
String lyric = text.substring(text.lastIndexOf("]") + 1).trim();//歌词
if (time.startsWith("0")) {
m = time.substring(1, 2);
if (time.substring(3).startsWith("0")) {
s = "0" + time.substring(4, 5);
} else {
s = time.substring(3, 5);
}
lyrics[index] = m + ":" + s + "--" + lyric;
index++;
}
}
reader.close();
bufferedReader.close();
} catch (Exception e1) {
e1.printStackTrace();
}
for (String lyric : lyrics) {
if (lyric != null && lyric.length() > 0) {
tableItem = new TableItem(table_1, SWT.NONE);
tableItem.setText(lyric.substring(6));
}
}
} else {
text_3.setText("感谢使用JAVA音乐播放器");
}
}
/**
* 改变列表的颜色
*
* @param Music (改变选中歌曲的颜色)
*/
private void updateList(String Music) {
if (Music.toLowerCase().endsWith("wav") || Music.endsWith("mp3")) {//对传进来的歌曲进行截取
Music = Music.substring(Music.lastIndexOf("\\") + 1, Music.lastIndexOf("."));
}
table.removeAll();
String[] musicList = BufferPlayList.toString().split("<-->");
TableItem item = null;
for (int i = 0; i < musicList.length; i++) {
if (!musicList[i].toLowerCase().endsWith(".lrc")) {
item = new TableItem(table, SWT.NONE);
item.setText(new String[]{"" + (i + 1), musicList[i].substring(musicList[i].lastIndexOf("\\") + 1, musicList[i].lastIndexOf("."))});
String music = musicList[i].trim().substring(musicList[i].lastIndexOf("\\") + 1, musicList[i].lastIndexOf("."));
if (Music.equalsIgnoreCase(music)) {
item.setBackground(SWTResourceManager.getColor(SWT.COLOR_BLUE));//将选中的行的颜色变为蓝色
} else {
item.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));//将非选中的行的颜色变为白色
}
}
}
}
/**
* 开始播放音乐
*
* @param playPath
* @author Administrator
*/
public void musicPlayerStart(String playPath) {//开始播放音乐
if (!playPath.endsWith("lrc") && !playPath.endsWith("wav")) {//为进来的歌曲名字不以 .wav 结尾的歌曲找到源歌曲路径
for (String lyric : playlist) {
if (lyric.toLowerCase().endsWith("wav") || lyric.endsWith("mp3")) {
if (lyric.substring(lyric.lastIndexOf("\\") + 1, lyric.lastIndexOf(".")).equals(playPath)) {
playPath = lyric;
}
}
}
}
File file = new File(playPath);
if (file.exists()) {
if (!"".equals(playPath) && playPath != null) {
if ("wav".equalsIgnoreCase(playPath.trim().substring(playPath.lastIndexOf(".") + 1))) {
try {
player.load(file);
player.start();
text_1.setText(playPath.substring(playPath.lastIndexOf("\\") + 1, playPath.lastIndexOf(".")));
AudioFile mp3 = AudioFileIO.read(new File(playPath));//获取播放流
totalPlayTime = mp3.getAudioHeader().getTrackLength(); //获取播放时间
System.out.println("歌曲总时间: " + totalPlayTime);
progressBar.setMaximum(100);//设置进度条的最大长度
progressBar.setSelection(100);
progressBar.setMinimum(0);//设置进度的条最小程度
if ("new".equalsIgnoreCase(playProgress.getState().toString())) {
playProgress.start();
} else if ("runable".equalsIgnoreCase(playProgress.getState().toString())) {
} else if ("TERMINATED".equalsIgnoreCase(playProgress.getState().toString())) {//已销毁
playProgress = new Thread(new PlayProgress(display));
playProgress.start();
} else {
playProgress.start();
}
} catch (Exception e1) {
e1.printStackTrace();
}
} else {
for (int i = 0; i < playlist.length; i++) {
String music = playlist[i].trim().substring(playlist[i].lastIndexOf("\\") + 1, playlist[i].lastIndexOf("."));
if (playPath.equalsIgnoreCase(music)) {
playPath = playlist[i].trim();
}
}
try {
player.load(file);
player.start();
text_1.setText(playPath.substring(playPath.lastIndexOf("\\") + 1, playPath.lastIndexOf(".")));
AudioFile mp3 = AudioFileIO.read(new File(playPath));//获取播放流
totalPlayTime = mp3.getAudioHeader().getTrackLength(); //获取播放时间
System.out.println("歌曲总时间: " + totalPlayTime);
progressBar.setMaximum(100);//设置进度条的最大长度
progressBar.setMinimum(0);//设置进度的条最小程度
if ("new".equalsIgnoreCase(playProgress.getState().toString())) {
playProgress.start();
} else if ("runable".equalsIgnoreCase(playProgress.getState().toString())) {
} else if ("TERMINATED".equalsIgnoreCase(playProgress.getState().toString())) {//已销毁
playProgress = new Thread(new PlayProgress(display));
playProgress.start();
} else {
playProgress.start();
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
} else {
Toolkit toolkit = Toolkit.getDefaultToolkit();
toolkit.beep();
MessageDialog.openError(shell, "错误提示", "请选择播放文件");
}
} else {
Toolkit toolkit = Toolkit.getDefaultToolkit();
toolkit.beep();
MessageDialog.openError(shell, "错误提示", "播放文件不存在");
}
}
/**
* 导入本地的播放文件(本地歌曲目录不存在,需要从新导入)
*
* @author Administrator
*/
public void inputMusicPlayerFile() {//导入本地的播放文件(本地歌曲目录不存在,需要从新导入)
JFileChooser choise = new JFileChooser();
choise.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
choise.setMultiSelectionEnabled(true);
choise.showOpenDialog(choise);
File[] files = choise.getSelectedFiles();//选中的文件
try {
File file = new File("D:/musicList.txt");//读取文件
table.removeAll();//去除列表中的全部歌曲
FileWriter writer = new FileWriter(file);//写出流
BufferedWriter bufferedWriter = new BufferedWriter(writer);//Buffere流
TableItem item = null;
BufferPlayList = new StringBuilder();
table.removeAll();
int index = 1;
for (File f : files) {
if (f.isFile()) {
bufferedWriter.write(f.toString());//将播放文件地址写入文件中
bufferedWriter.newLine();//换行
bufferedWriter.flush();//刷新
if (f.toString().toLowerCase().endsWith("wav") || f.toString().endsWith("mp3")) {//只有音乐文件才能添加到播放列表中
item = new TableItem(table, SWT.NONE);//新建一个列表的行
item.setText(new String[]{"" + index, f.toString().substring(f.toString().lastIndexOf("\\") + 1, f.toString().lastIndexOf("."))});
index++;
}
BufferPlayList.append(f.toString()).append("<-->");
playlist = new String[BufferPlayList.length()];
playlist = BufferPlayList.toString().split("<-->");
}
}
bufferedWriter.close();//结束写入流
writer.close();//结束写入流
} catch (IOException e1) {
e1.printStackTrace();
}
}
/**
* 获取本地的播放文件(本地歌曲目录已存在)
*
* @author Administrator
*/
public void getMusicPlayerFile() {//获取本地的播放文件(本地歌曲目录已存在)
TableItem[] items = table.getSelection();
if (items.length <= 0) {
File file = new File("D:/musicList.txt");
if (!file.exists()) {
Toolkit toolkit = Toolkit.getDefaultToolkit();
toolkit.beep();
MessageDialog.openError(shell, "错误提示", "丢失歌曲文件目录索引,请重新添加文件");
inputMusicPlayerFile();//如果文件不存在就从新导入文件
} else {
FileReader reader;
BufferPlayList = new StringBuilder();
try {
reader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(reader);
String txt = "";
TableItem item;
int index = 1;
while ((txt = bufferedReader.readLine()) != null) {
if (txt.toLowerCase().endsWith("wav") || txt.endsWith("mp3")) {
item = new TableItem(table, SWT.NONE);
item.setText(new String[]{"" + index, txt.substring(txt.lastIndexOf("\\") + 1, txt.lastIndexOf("."))});
index++;
}
BufferPlayList.append(txt).append("<-->");
playlist = new String[BufferPlayList.length()];
playlist = BufferPlayList.toString().split("<-->");
}
bufferedReader.close();
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 时间转换
*
* @param time
* @return
*/
public String getTime(int time) {
String temp = "";
if (lyricTimes % 2 < 10) {
temp = lyricTimes / 60 + ":0" + lyricTimes % 2;
} else {
temp = lyricTimes / 60 + ":" + lyricTimes % 2;
}
if (lyricTimes < 60) {
if (lyricTimes < 10) {
temp = "0:0" + lyricTimes;
} else {
temp = "0:" + lyricTimes;
}
} else {
if (lyricTimes % 60 < 10) {
temp = lyricTimes / 60 + ":0" + lyricTimes % 60;
} else {
temp = lyricTimes / 60 + ":" + lyricTimes % 60;
}
}
return temp;
}
/**
* 销毁会进程
*
* @author Administrator
*/
public void distory() {//销毁会进程
Timer timer = new Timer();
timer.schedule(new Time(), 0, 1 * 1000);
}
/**
* 系统退出延时器
*
* @author Administrator
*/
static class Time extends TimerTask {//系统退出延时器
Toolkit toolkit = Toolkit.getDefaultToolkit();
int time = 1;
@Override
public void run() {
if (time > 0) {
//toolkit.beep();
time--;
} else {
System.exit(0);
}
}
}
/**
* 音乐时间、进度条 线程
*
* @author Administrator
*/
class TimerTaskPlayProgress extends TimerTask {
private int totalPlayTime;
private Display display;
private int autoAddLyricTime = 0;//歌词的时间
private int autoAddShowTime = 0;//文本框显示的歌曲播放的时间
private int autoAddprogressBarTime = 0;//进度条的时间
private String tempLyric = "";
public TimerTaskPlayProgress(Display display) {
this.autoAddShowTime = totalPlayTime;
this.display = display;
}
@Override
@SuppressWarnings("static-access")
public void run() {
for (int i = 0; i < totalPlayTime; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//这个是同步主线程的资源而不发生异常
Display.getDefault().asyncExec(() -> {
autoAddprogressBarTime++;//进度条的时间
autoAddLyricTime++; //歌词的时间
autoAddShowTime--; //文本框显示的歌曲播放的时间
System.out.println(autoAddLyricTime);
if (haslyric) {//如果这首歌曲拥有歌词
tempLyric = getTime(lyricTimes);
for (String lyric : lyrics) {
if (lyric != null && lyric.length() > 0) {
if (tempLyric.trim().equals(lyric.substring(0, 4))) {
text_3.setText(lyric.substring(6));
}
}
}
}
text.setText((autoAddShowTime) / 60 + " : " + (autoAddShowTime) % 60 + "/" + (totalPlayTime) / 60 + " : " + (totalPlayTime) % 60);//在文本框中显示剩余时间
progressBar.setSelection(autoAddprogressBarTime * 100 / totalPlayTime);//进度条递增
if (autoAddShowTime == 0) {//如果歌曲播放时间为0时
progressBar.setSelection(0);
text.setText("00:00/00:00");
player.stop();
}
});
}
}
}
/**
* 音乐时间、进度条 线程
*
* @author Administrator
*/
class PlayProgress implements Runnable {
private int totalPlayTime;
private Display display;
private int autoAddLyricTime = 0;//歌词的时间
private int autoAddShowTime = 0;//文本框显示的歌曲播放的时间
private int autoAddprogressBarTime = 0;//进度条的时间
private String tempLyric = "";
public PlayProgress(Display display) {
this.autoAddShowTime = totalPlayTime;
this.display = display;
}
@Override
@SuppressWarnings("static-access")
public void run() {
for (int i = 0; i < totalPlayTime; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//这个是同步主线程的资源而不发生异常
Display.getDefault().asyncExec(() -> {
autoAddprogressBarTime++;//进度条的时间
autoAddLyricTime++; //歌词的时间
autoAddShowTime--; //文本框显示的歌曲播放的时间
System.out.println(autoAddLyricTime);
if (haslyric) {//如果这首歌曲拥有歌词
tempLyric = getTime(lyricTimes);
for (String lyric : lyrics) {
if (lyric != null && lyric.length() > 0) {
if (tempLyric.trim().equals(lyric.substring(0, 4))) {
text_3.setText(lyric.substring(6));
}
}
}
}
text.setText((autoAddShowTime) / 60 + " : " + (autoAddShowTime) % 60 + "/" + (totalPlayTime) / 60 + " : " + (totalPlayTime) % 60);//在文本框中显示剩余时间
progressBar.setSelection(autoAddprogressBarTime * 100 / totalPlayTime);//进度条递增
if (autoAddShowTime == 0) {//如果歌曲播放时间为0时
progressBar.setSelection(0);
text.setText("00:00/00:00");
player.stop();
}
});
}
}
}
}
| 40,680 | Java | .java | xuhyacinth/MusicPlayer | 9 | 0 | 0 | 2020-12-13T04:23:25Z | 2022-03-15T03:58:12Z |
MusicPlayerDemo.java | /FileExtraction/Java_unseen/xuhyacinth_MusicPlayer/src/com/xu/music/player/test/MusicPlayerDemo.java | package com.xu.music.player.test;
import com.xu.music.player.player.Player;
import com.xu.music.player.player.XMusic;
import com.xu.music.player.tray.MusicPlayerTray;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.*;
import org.eclipse.wb.swt.SWTResourceManager;
import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
@SuppressWarnings(value = "all")
public class MusicPlayerDemo {
private static int totalPlayTime;
protected Shell shell;
private Display display;
private Player player = XMusic.player();
private Button button;
private Table table;
private Tray tray;
private String playPath;
private Text text;
private Thread playProgress;
private ProgressBar progressBar;
private Text text_1;
private int clickX, clickY;
private Boolean click = false;
private Label label_5;
private int judeg = 0;
private StringBuilder BufferPlayList;
private Text text_2;
private Text text_3;
private int lyricTimes = 0;
private String[] lyrics = new String[200];
private boolean haslyric = false;
private Table table_1;
private String[] playlist;
private GC gc;
/**
* Launch the application.
*
* @param args
*/
public static void main(String[] args) {
try {
MusicPlayerDemo window = new MusicPlayerDemo();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Open the window.
*/
public void open() {
display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
* Create contents of the window.
*/
protected void createContents() {
shell = new Shell(SWT.NONE);
shell.setImage(SWTResourceManager.getImage(MusicPlayerDemo.class, "/com/xu/musicplayer/image/music.png"));
shell.setSize(new Point(1000, 645));
shell.setSize(889, 485);
shell.setText("音乐");
shell.setLocation((display.getClientArea().width - shell.getSize().x) / 2,
(display.getClientArea().height - shell.getSize().y) / 2);
shell.setLayout(new FillLayout(SWT.HORIZONTAL));
// 托盘引入
tray = display.getSystemTray();
MusicPlayerTray trayutil = new MusicPlayerTray(shell, tray);
trayutil.tray();
Composite composite = new Composite(shell, SWT.NO_RADIO_GROUP);
composite.setLayout(new FormLayout());
button = new Button(composite, SWT.NONE);
button.setImage(SWTResourceManager.getImage(MusicPlayerDemo.class, "/com/xu/musicplayer/image/addMusic.png"));
FormData fd_button = new FormData();
fd_button.right = new FormAttachment(100, -803);
fd_button.left = new FormAttachment(0);
button.setLayoutData(fd_button);
button.setText(" 添 加 ");
FormData fd_composite_2 = new FormData();
fd_composite_2.left = new FormAttachment(0, 105);
fd_composite_2.bottom = new FormAttachment(100, -10);
fd_composite_2.top = new FormAttachment(0, 382);
fd_composite_2.right = new FormAttachment(100, -123);
table = new Table(composite, SWT.FULL_SELECTION);
FormData fd_table = new FormData();
fd_table.top = new FormAttachment(button, 6);
fd_table.left = new FormAttachment(0);
fd_table.right = new FormAttachment(100, -689);
table.setLayoutData(fd_table);
table.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_LIGHT_SHADOW));
table.setHeaderVisible(true);
table.setLinesVisible(true);
TableColumn tableColumn_2 = new TableColumn(table, SWT.NONE);
tableColumn_2.setWidth(37);
tableColumn_2.setText("编号");
TableColumn tableColumn_1 = new TableColumn(table, SWT.NONE);
tableColumn_1.setWidth(244);
tableColumn_1.setText("默 认 列 表");
Composite composite_1 = new Composite(composite, SWT.NONE);
fd_button.top = new FormAttachment(composite_1, 6);
composite_1.setBackgroundMode(SWT.INHERIT_DEFAULT);
composite_1.setBackground(SWTResourceManager.getColor(SWT.COLOR_CYAN));
FormData fd_composite_1 = new FormData();
fd_composite_1.top = new FormAttachment(0);
fd_composite_1.left = new FormAttachment(0);
fd_composite_1.right = new FormAttachment(0, 887);
fd_composite_1.bottom = new FormAttachment(0, 56);
composite_1.setLayoutData(fd_composite_1);
Label label = new Label(composite_1, SWT.NONE);
label.setImage(SWTResourceManager.getImage(MusicPlayerDemo.class, "/com/xu/musicplayer/image/hand.png"));
label.setBounds(0, 0, 56, 56);
gc = new GC(label);
gc.fillOval(0, 0, 56, 56);
gc.setBackground(SWTResourceManager.getColor(new RGB(11, 22, 22)));
gc.dispose();
final Label label_1 = new Label(composite_1, SWT.NONE);
label_1.setImage(SWTResourceManager.getImage(MusicPlayerDemo.class, "/com/xu/musicplayer/image/minus_1.png"));
label_1.setBounds(817, 0, 32, 32);
final Label label_2 = new Label(composite_1, SWT.NONE);
label_2.setImage(SWTResourceManager.getImage(MusicPlayerDemo.class, "/com/xu/musicplayer/image/delete_1.png"));
label_2.setBounds(855, 0, 32, 32);
Label lblNewLabel = new Label(composite_1, SWT.NONE);
lblNewLabel.setBounds(72, 20, 61, 17);
lblNewLabel.setText("月色深蓝");
Composite composite_3 = new Composite(composite, SWT.NONE);
fd_table.bottom = new FormAttachment(composite_3, -6);
composite_3.setBackgroundMode(SWT.INHERIT_DEFAULT);
composite_3.setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY));
FormData fd_composite_3 = new FormData();
fd_composite_3.top = new FormAttachment(0, 409);
fd_composite_3.bottom = new FormAttachment(100);
fd_composite_3.right = new FormAttachment(composite_1, 0, SWT.RIGHT);
text_2 = new Text(composite_1, SWT.NONE);
text_2.setForeground(SWTResourceManager.getColor(SWT.COLOR_CYAN));
text_2.setText("111");
text_2.setFont(SWTResourceManager.getFont("Microsoft YaHei UI", 16, SWT.NORMAL));
text_2.setBounds(281, 12, 336, 32);
Label label_6 = new Label(composite_1, SWT.NONE);
label_6.setImage(SWTResourceManager.getImage(MusicPlayerDemo.class, "/com/xu/musicplayer/image/find.png"));
label_6.setBounds(640, 12, 32, 32);
fd_composite_3.left = new FormAttachment(0);
composite_3.setLayoutData(fd_composite_3);
Label label_3 = new Label(composite_3, SWT.NONE);
label_3.setImage(SWTResourceManager.getImage(MusicPlayerDemo.class, "/com/xu/musicplayer/image/prev.png"));
label_3.setBounds(24, 27, 24, 24);
Composite composite_2 = new Composite(composite_3, SWT.NONE);
composite_2.setLocation(225, 48);
composite_2.setSize(452, 10);
composite_2.setLayout(new FillLayout(SWT.HORIZONTAL));
progressBar = new ProgressBar(composite_2, SWT.NONE);
progressBar.setBounds(0, 0, 655, 27);//设置进度条的位置
Label label_4 = new Label(composite_3, SWT.NONE);
label_4.setImage(SWTResourceManager.getImage(MusicPlayerDemo.class, "/com/xu/musicplayer/image/next.png"));
label_4.setBounds(132, 27, 24, 24);
text_1 = new Text(composite_3, SWT.READ_ONLY);
text_1.setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY));
text_1.setBounds(225, 10, 287, 27);
text_1.setForeground(SWTResourceManager.getColor(SWT.COLOR_GREEN));
text_1.setFont(SWTResourceManager.getFont("Microsoft YaHei UI", 12, SWT.NORMAL));
text_1.setEnabled(false);
text = new Text(composite_3, SWT.READ_ONLY | SWT.CENTER);
text.setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY));
text.setBounds(541, 10, 136, 27);
text.setForeground(SWTResourceManager.getColor(SWT.COLOR_GREEN));
text.setFont(SWTResourceManager.getFont("Microsoft YaHei UI", 12, SWT.NORMAL));
text.setEnabled(false);
label_5 = new Label(composite_3, SWT.NONE);
label_5.setImage(SWTResourceManager.getImage(MusicPlayerDemo.class, "/com/xu/musicplayer/image/begin.png"));
label_5.setBounds(79, 27, 24, 24);
Button button_1 = new Button(composite, SWT.NONE);
button_1.setText("扫 描");
button_1.setImage(SWTResourceManager.getImage(MusicPlayerDemo.class, "/com/xu/musicplayer/image/search.png"));
FormData fd_button_1 = new FormData();
fd_button_1.left = new FormAttachment(table, -84);
fd_button_1.bottom = new FormAttachment(button, 0, SWT.BOTTOM);
fd_button_1.right = new FormAttachment(table, 0, SWT.RIGHT);
button_1.setLayoutData(fd_button_1);
text_3 = new Text(composite, SWT.READ_ONLY | SWT.CENTER);
text_3.setFont(SWTResourceManager.getFont("Microsoft YaHei UI", 16, SWT.NORMAL));
text_3.setForeground(SWTResourceManager.getColor(SWT.COLOR_RED));
FormData fd_text_3 = new FormData();
fd_text_3.right = new FormAttachment(table, 629, SWT.RIGHT);
fd_text_3.top = new FormAttachment(composite_1, 313);
fd_text_3.bottom = new FormAttachment(composite_3, -6);
fd_text_3.left = new FormAttachment(table, 6);
text_3.setLayoutData(fd_text_3);
table_1 = new Table(composite, SWT.FULL_SELECTION);
FormData fd_table_1 = new FormData();
fd_table_1.bottom = new FormAttachment(text_3, -6);
fd_table_1.right = new FormAttachment(text_3, 0, SWT.RIGHT);
fd_table_1.top = new FormAttachment(table, 0, SWT.TOP);
fd_table_1.left = new FormAttachment(table, 6);
table_1.setLayoutData(fd_table_1);
table_1.setHeaderVisible(true);
table_1.setLinesVisible(true);
TableColumn tableColumn = new TableColumn(table_1, SWT.NONE);
tableColumn.setWidth(621);
tableColumn.setText(" 歌词");
button_1.addMouseListener(new MouseAdapter() {
@Override
public void mouseUp(MouseEvent e) {
//new SearchMusic().open();//寻找播放文件的界面
}
});
playProgress = new Thread(new PlayProgress(display));
//playProgress.setDaemon(true);
getMusicPlayerFile();//读取本地播放文件
//选择菜单中的音乐
table.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
TableItem[] items = table.getSelection();
playPath = items[0].getText(1).trim();
String[] musicList = BufferPlayList.toString().split("<-->");
for (String lyric : musicList) {
if (lyric.substring(lyric.lastIndexOf("\\") + 1, lyric.lastIndexOf(".")).equals(playPath)) {
playPath = lyric;
}
}
updateList(playPath);
}
});
//导入本地播放文件
button.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
inputMusicPlayerFile();
}
});
//退出
label_2.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
label_2.setImage(SWTResourceManager.getImage(MusicPlayerDemo.class, "/com/xu/musicplayer/image/delete_2.png"));
}
@Override
public void mouseUp(MouseEvent e) {
label_2.setImage(SWTResourceManager.getImage(MusicPlayerDemo.class, "/com/xu/musicplayer/image/delete_1.png"));
tray.dispose();
distory();
}
});
label_2.addMouseTrackListener(new MouseTrackAdapter() {
@Override
public void mouseExit(MouseEvent e) {
label_2.setImage(SWTResourceManager.getImage(MusicPlayerDemo.class, "/com/xu/musicplayer/image/delete_1.png"));
}
@Override
public void mouseHover(MouseEvent e) {
label_2.setImage(SWTResourceManager.getImage(MusicPlayerDemo.class, "/com/xu/musicplayer/image/delete_2.png"));
label_2.setToolTipText("退出");
}
});
//缩小
label_1.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
label_1.setImage(SWTResourceManager.getImage(MusicPlayerDemo.class, "/com/xu/musicplayer/image/minus_2.png"));
}
@Override
public void mouseUp(MouseEvent e) {
label_1.setImage(SWTResourceManager.getImage(MusicPlayerDemo.class, "/com/xu/musicplayer/image/minus_1.png"));
shell.setMinimized(true);
}
});
label_1.addMouseTrackListener(new MouseTrackAdapter() {
@Override
public void mouseExit(MouseEvent e) {
label_1.setImage(SWTResourceManager.getImage(MusicPlayerDemo.class, "/com/xu/musicplayer/image/minus_1.png"));
}
@Override
public void mouseHover(MouseEvent e) {
label_1.setImage(SWTResourceManager.getImage(MusicPlayerDemo.class, "/com/xu/musicplayer/image/minus_2.png"));
label_1.setToolTipText("最小化");
}
});
progressBar.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
System.out.println(e.widget);
}
});
//界面移动
composite_1.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
click = true;
clickX = e.x;
clickY = e.y;
}
@Override
public void mouseUp(MouseEvent e) {
click = false;
}
});
composite_1.addMouseMoveListener(arg0 -> {//当鼠标按下的时候执行这条语句
if (click) {
shell.setLocation(shell.getLocation().x - clickX + arg0.x, shell.getLocation().y - clickY + arg0.y);
}
});
//播放按钮
label_5.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
}
@SuppressWarnings("deprecation")
@Override
public void mouseUp(MouseEvent e) {
judeg++;
if (judeg % 2 != 0) {//单击音乐开始
if (playPath == null || "".equals(playPath)) {
Toolkit toolkit = Toolkit.getDefaultToolkit();
toolkit.beep();
MessageDialog.openError(shell, "错误提示", "请选择播放文件");
} else {
label_5.setImage(SWTResourceManager.getImage(MusicPlayerDemo.class, "/com/xu/musicplayer/image/stop.png"));
musicPlayerStart(playPath);
lyric(playPath);
}
} else {//单击音乐停止
label_5.setImage(SWTResourceManager.getImage(MusicPlayerDemo.class, "/com/xu/musicplayer/image/begin.png"));
playProgress.stop();
progressBar.setSelection(0);
player.stop();
text.setText("");
}
if (judeg == 4) {
judeg = 0;
}
}
});
//上一曲
label_3.addMouseListener(new MouseAdapter() {
@Override
public void mouseUp(MouseEvent e) {
if (text_1.getText().trim() == null || "".equals(text_1.getText().trim())) {
String[] musicList = BufferPlayList.toString().split("<-->");
int playLists = new Random().nextInt(musicList.length) + 1;
if (!musicList[playLists].endsWith(".lrc")) {
playPath = musicList[playLists];
} else {
if (playLists == musicList.length) {
playPath = musicList[playLists - 1];
} else if (playLists == 0) {
playPath = musicList[playLists + 1];
} else {
playPath = musicList[playLists + 1];
}
}
label_5.setImage(SWTResourceManager.getImage(MusicPlayerDemo.class, "/com/xu/musicplayer/image/stop.png"));
haslyric = false;
totalMethod(playPath.trim());
judeg = 1;
} else {
//结束现在所有
endAll();
String[] musicList = BufferPlayList.toString().split("<-->");
int playLists = new Random().nextInt(musicList.length) + 1;
if (!musicList[playLists].endsWith(".lrc")) {
playPath = musicList[playLists];
} else {
if (playLists == musicList.length) {
playPath = musicList[playLists - 1];
} else if (playLists == 0) {
playPath = musicList[playLists + 1];
} else {
playPath = musicList[playLists + 1];
}
}
label_5.setImage(SWTResourceManager.getImage(MusicPlayerDemo.class, "/com/xu/musicplayer/image/stop.png"));
haslyric = false;
totalMethod(playPath.trim());
judeg = 1;
}
}
});
//下一曲
label_4.addMouseListener(new MouseAdapter() {
@Override
public void mouseUp(MouseEvent e) {
if (text_1.getText().trim() == null || "".equals(text_1.getText().trim())) {
int playLists = new Random().nextInt(playlist.length);
if (!playlist[playLists].endsWith(".lrc")) {
playPath = playlist[playLists];
} else {
if (playLists == playlist.length) {
playPath = playlist[playLists - 1];
} else if (playLists == 0) {
playPath = playlist[playLists + 1];
} else {
playPath = playlist[playLists + 1];
}
}
label_5.setImage(SWTResourceManager.getImage(MusicPlayerDemo.class, "/com/xu/musicplayer/image/stop.png"));
haslyric = false;
totalMethod(playPath.trim());
judeg = 1;
} else {
//结束现在所有
endAll();
int playLists = new Random().nextInt(playlist.length);
if (!playlist[playLists].endsWith(".lrc")) {
playPath = playlist[playLists];
} else {
if (playLists == playlist.length) {
playPath = playlist[playLists - 1];
} else if (playLists == 0) {
playPath = playlist[playLists + 1];
} else {
playPath = playlist[playLists + 1];
}
}
label_5.setImage(SWTResourceManager.getImage(MusicPlayerDemo.class, "/com/xu/musicplayer/image/stop.png"));
haslyric = false;
totalMethod(playPath.trim());
judeg = 1;
}
}
});
}
@SuppressWarnings("deprecation")
public void endAll() {
//结束现在所有
if ("RUNNABLE".equalsIgnoreCase(playProgress.getState().toString())) {//在运行
playProgress.stop();
}
try {
player.end();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
progressBar.setSelection(0);
}
/**
* 调用所需的方法
*
* @param playpath
*/
public void totalMethod(String playpath) {
musicPlayerStart(playPath.trim());//开始音乐
lyric(playPath.trim());//显示歌词
updateList(playPath.trim());//改变行的颜色
}
/**
* 显示歌词
*
* @param playPaths
*/
private void lyric(String playPaths) {
lyricTimes = 0;
TableItem tableItem = null;
if (playPaths.endsWith("wav") || playPaths.endsWith("mp3")) {//对传进来的歌曲进行截取
playPaths = playPaths.substring(playPaths.lastIndexOf("\\") + 1, playPaths.lastIndexOf(".")).trim();
}
for (String lyric : playlist) {//为歌词匹配路径
if (lyric.endsWith("lrc") || lyric.endsWith("LRC")) {
if (lyric.trim().substring(lyric.lastIndexOf("\\") + 1, lyric.lastIndexOf(".")).equals(playPaths)) {
playPaths = lyric;
haslyric = true;
break;
} else {
haslyric = false;
}
}
}
System.out.println("是否拥有歌词: " + haslyric + "\n歌词名: " + playPaths);
if (haslyric) {
String m;//分钟
String s;//秒钟
int index = 0;
try {
FileReader reader = new FileReader(new File(playPaths));
BufferedReader bufferedReader = new BufferedReader(reader);
String text;
while ((text = bufferedReader.readLine()) != null) {
String time = text.substring(1, text.lastIndexOf("]"));//歌曲时间
String lyric = text.substring(text.lastIndexOf("]") + 1).trim();//歌词
if (time.startsWith("0")) {
m = time.substring(1, 2);
if (time.substring(3).startsWith("0")) {
s = "0" + time.substring(4, 5);
} else {
s = time.substring(3, 5);
}
lyrics[index] = m + ":" + s + "--" + lyric;
index++;
}
}
reader.close();
bufferedReader.close();
} catch (Exception e1) {
e1.printStackTrace();
}
for (String lyric : lyrics) {
if (lyric != null && lyric.length() > 0) {
tableItem = new TableItem(table_1, SWT.NONE);
tableItem.setText(lyric.substring(6));
}
}
} else {
text_3.setText("感谢使用JAVA音乐播放器");
}
}
/**
* 改变列表的颜色
*
* @param Music (改变选中歌曲的颜色)
*/
private void updateList(String Music) {
if (Music.toLowerCase().endsWith("wav") || Music.endsWith("mp3")) {//对传进来的歌曲进行截取
Music = Music.substring(Music.lastIndexOf("\\") + 1, Music.lastIndexOf("."));
}
table.removeAll();
String[] musicList = BufferPlayList.toString().split("<-->");
TableItem item = null;
for (int i = 0; i < musicList.length; i++) {
if (!musicList[i].toLowerCase().endsWith(".lrc")) {
item = new TableItem(table, SWT.NONE);
item.setText(new String[]{"" + (i + 1), musicList[i].substring(musicList[i].lastIndexOf("\\") + 1, musicList[i].lastIndexOf("."))});
String music = musicList[i].trim().substring(musicList[i].lastIndexOf("\\") + 1, musicList[i].lastIndexOf("."));
if (Music.equalsIgnoreCase(music)) {
item.setBackground(SWTResourceManager.getColor(SWT.COLOR_BLUE));//将选中的行的颜色变为蓝色
} else {
item.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));//将非选中的行的颜色变为白色
}
}
}
}
/**
* 开始播放音乐
*
* @param playPath
* @author Administrator
*/
public void musicPlayerStart(String playPath) {//开始播放音乐
if (!playPath.endsWith("lrc") && !playPath.endsWith("wav")) {//为进来的歌曲名字不以 .wav 结尾的歌曲找到源歌曲路径
for (String lyric : playlist) {
if (lyric.toLowerCase().endsWith("wav") || lyric.endsWith("mp3")) {
if (lyric.substring(lyric.lastIndexOf("\\") + 1, lyric.lastIndexOf(".")).equals(playPath)) {
playPath = lyric;
}
}
}
}
File file = new File(playPath);
if (file.exists()) {
if (!"".equals(playPath) && playPath != null) {
if ("wav".equalsIgnoreCase(playPath.trim().substring(playPath.lastIndexOf(".") + 1))) {
try {
player.load(file);
player.start();
text_1.setText(playPath.substring(playPath.lastIndexOf("\\") + 1, playPath.lastIndexOf(".")));
AudioFile mp3 = AudioFileIO.read(new File(playPath));//获取播放流
totalPlayTime = mp3.getAudioHeader().getTrackLength(); //获取播放时间
System.out.println("歌曲总时间: " + totalPlayTime);
progressBar.setMaximum(100);//设置进度条的最大长度
progressBar.setSelection(100);
progressBar.setMinimum(0);//设置进度的条最小程度
if ("new".equalsIgnoreCase(playProgress.getState().toString())) {
playProgress.start();
} else if ("runable".equalsIgnoreCase(playProgress.getState().toString())) {
} else if ("TERMINATED".equalsIgnoreCase(playProgress.getState().toString())) {//已销毁
playProgress = new Thread(new PlayProgress(display));
playProgress.start();
} else {
playProgress.start();
}
} catch (Exception e1) {
e1.printStackTrace();
}
} else {
for (int i = 0; i < playlist.length; i++) {
String music = playlist[i].trim().substring(playlist[i].lastIndexOf("\\") + 1, playlist[i].lastIndexOf("."));
if (playPath.equalsIgnoreCase(music)) {
playPath = playlist[i].trim();
}
}
try {
player.load(file);
player.start();
text_1.setText(playPath.substring(playPath.lastIndexOf("\\") + 1, playPath.lastIndexOf(".")));
AudioFile mp3 = AudioFileIO.read(new File(playPath));//获取播放流
totalPlayTime = mp3.getAudioHeader().getTrackLength(); //获取播放时间
System.out.println("歌曲总时间: " + totalPlayTime);
progressBar.setMaximum(100);//设置进度条的最大长度
progressBar.setMinimum(0);//设置进度的条最小程度
if ("new".equalsIgnoreCase(playProgress.getState().toString())) {
playProgress.start();
} else if ("runable".equalsIgnoreCase(playProgress.getState().toString())) {
} else if ("TERMINATED".equalsIgnoreCase(playProgress.getState().toString())) {//已销毁
playProgress = new Thread(new PlayProgress(display));
playProgress.start();
} else {
playProgress.start();
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
} else {
Toolkit toolkit = Toolkit.getDefaultToolkit();
toolkit.beep();
MessageDialog.openError(shell, "错误提示", "请选择播放文件");
}
} else {
Toolkit toolkit = Toolkit.getDefaultToolkit();
toolkit.beep();
MessageDialog.openError(shell, "错误提示", "播放文件不存在");
}
}
/**
* 导入本地的播放文件(本地歌曲目录不存在,需要从新导入)
*
* @author Administrator
*/
public void inputMusicPlayerFile() {//导入本地的播放文件(本地歌曲目录不存在,需要从新导入)
JFileChooser choise = new JFileChooser();
choise.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
choise.setMultiSelectionEnabled(true);
choise.showOpenDialog(choise);
File[] files = choise.getSelectedFiles();//选中的文件
try {
File file = new File("D:/musicList.txt");//读取文件
table.removeAll();//去除列表中的全部歌曲
FileWriter writer = new FileWriter(file);//写出流
BufferedWriter bufferedWriter = new BufferedWriter(writer);//Buffere流
TableItem item = null;
BufferPlayList = new StringBuilder();
table.removeAll();
int index = 1;
for (File f : files) {
if (f.isFile()) {
bufferedWriter.write(f.toString());//将播放文件地址写入文件中
bufferedWriter.newLine();//换行
bufferedWriter.flush();//刷新
if (f.toString().toLowerCase().endsWith("wav") || f.toString().endsWith("mp3")) {//只有音乐文件才能添加到播放列表中
item = new TableItem(table, SWT.NONE);//新建一个列表的行
item.setText(new String[]{"" + index, f.toString().substring(f.toString().lastIndexOf("\\") + 1, f.toString().lastIndexOf("."))});
index++;
}
BufferPlayList.append(f.toString()).append("<-->");
playlist = new String[BufferPlayList.length()];
playlist = BufferPlayList.toString().split("<-->");
}
}
bufferedWriter.close();//结束写入流
writer.close();//结束写入流
} catch (IOException e1) {
e1.printStackTrace();
}
}
/**
* 获取本地的播放文件(本地歌曲目录已存在)
*
* @author Administrator
*/
public void getMusicPlayerFile() {//获取本地的播放文件(本地歌曲目录已存在)
TableItem[] items = table.getSelection();
if (items.length <= 0) {
File file = new File("D:/musicList.txt");
if (!file.exists()) {
Toolkit toolkit = Toolkit.getDefaultToolkit();
toolkit.beep();
MessageDialog.openError(shell, "错误提示", "丢失歌曲文件目录索引,请重新添加文件");
inputMusicPlayerFile();//如果文件不存在就从新导入文件
} else {
FileReader reader;
BufferPlayList = new StringBuilder();
try {
reader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(reader);
String txt = "";
TableItem item;
int index = 1;
while ((txt = bufferedReader.readLine()) != null) {
if (txt.toLowerCase().endsWith("wav") || txt.endsWith("mp3")) {
item = new TableItem(table, SWT.NONE);
item.setText(new String[]{"" + index, txt.substring(txt.lastIndexOf("\\") + 1, txt.lastIndexOf("."))});
index++;
}
BufferPlayList.append(txt).append("<-->");
playlist = new String[BufferPlayList.length()];
playlist = BufferPlayList.toString().split("<-->");
}
bufferedReader.close();
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 时间转换
*
* @param time
* @return
*/
public String getTime(int time) {
String temp = "";
if (lyricTimes % 2 < 10) {
temp = lyricTimes / 60 + ":0" + lyricTimes % 2;
} else {
temp = lyricTimes / 60 + ":" + lyricTimes % 2;
}
if (lyricTimes < 60) {
if (lyricTimes < 10) {
temp = "0:0" + lyricTimes;
} else {
temp = "0:" + lyricTimes;
}
} else {
if (lyricTimes % 60 < 10) {
temp = lyricTimes / 60 + ":0" + lyricTimes % 60;
} else {
temp = lyricTimes / 60 + ":" + lyricTimes % 60;
}
}
return temp;
}
/**
* 销毁会进程
*
* @author Administrator
*/
public void distory() {//销毁会进程
Timer timer = new Timer();
timer.schedule(new Time(), 0, 1 * 1000);
}
/**
* 系统退出延时器
*
* @author Administrator
*/
static class Time extends TimerTask {//系统退出延时器
Toolkit toolkit = Toolkit.getDefaultToolkit();
int time = 1;
@Override
public void run() {
if (time > 0) {
//toolkit.beep();
time--;
} else {
System.exit(0);
}
}
}
/**
* 音乐时间、进度条 线程
*
* @author Administrator
*/
class TimerTaskPlayProgress extends TimerTask {
private int totalPlayTime;
private Display display;
private int autoAddLyricTime = 0;//歌词的时间
private int autoAddShowTime = 0;//文本框显示的歌曲播放的时间
private int autoAddprogressBarTime = 0;//进度条的时间
private String tempLyric = "";
public TimerTaskPlayProgress(Display display) {
this.autoAddShowTime = totalPlayTime;
this.display = display;
}
@Override
@SuppressWarnings("static-access")
public void run() {
for (int i = 0; i < totalPlayTime; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//这个是同步主线程的资源而不发生异常
Display.getDefault().asyncExec(() -> {
autoAddprogressBarTime++;//进度条的时间
autoAddLyricTime++; //歌词的时间
autoAddShowTime--; //文本框显示的歌曲播放的时间
System.out.println(autoAddLyricTime);
if (haslyric) {//如果这首歌曲拥有歌词
tempLyric = getTime(lyricTimes);
for (String lyric : lyrics) {
if (lyric != null && lyric.length() > 0) {
if (tempLyric.trim().equals(lyric.substring(0, 4))) {
text_3.setText(lyric.substring(6));
}
}
}
}
text.setText((autoAddShowTime) / 60 + " : " + (autoAddShowTime) % 60 + "/" + (totalPlayTime) / 60 + " : " + (totalPlayTime) % 60);//在文本框中显示剩余时间
progressBar.setSelection(autoAddprogressBarTime * 100 / totalPlayTime);//进度条递增
if (autoAddShowTime == 0) {//如果歌曲播放时间为0时
progressBar.setSelection(0);
text.setText("00:00/00:00");
player.stop();
}
});
}
}
}
/**
* 音乐时间、进度条 线程
*
* @author Administrator
*/
class PlayProgress implements Runnable {
private int totalPlayTime;
private Display display;
private int autoAddLyricTime = 0;//歌词的时间
private int autoAddShowTime = 0;//文本框显示的歌曲播放的时间
private int autoAddprogressBarTime = 0;//进度条的时间
private String tempLyric = "";
public PlayProgress(Display display) {
this.autoAddShowTime = totalPlayTime;
this.display = display;
}
@Override
@SuppressWarnings("static-access")
public void run() {
for (int i = 0; i < totalPlayTime; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//这个是同步主线程的资源而不发生异常
Display.getDefault().asyncExec(() -> {
autoAddprogressBarTime++;//进度条的时间
autoAddLyricTime++; //歌词的时间
autoAddShowTime--; //文本框显示的歌曲播放的时间
System.out.println(autoAddLyricTime);
if (haslyric) {//如果这首歌曲拥有歌词
tempLyric = getTime(lyricTimes);
for (String lyric : lyrics) {
if (lyric != null && lyric.length() > 0) {
if (tempLyric.trim().equals(lyric.substring(0, 4))) {
text_3.setText(lyric.substring(6));
}
}
}
}
text.setText((autoAddShowTime) / 60 + " : " + (autoAddShowTime) % 60 + "/" + (totalPlayTime) / 60 + " : " + (totalPlayTime) % 60);//在文本框中显示剩余时间
progressBar.setSelection(autoAddprogressBarTime * 100 / totalPlayTime);//进度条递增
if (autoAddShowTime == 0) {//如果歌曲播放时间为0时
progressBar.setSelection(0);
text.setText("00:00/00:00");
player.stop();
}
});
}
}
}
}
| 40,680 | Java | .java | xuhyacinth/MusicPlayer | 9 | 0 | 0 | 2020-12-13T04:23:25Z | 2022-03-15T03:58:12Z |
MusicPlayer.java | /FileExtraction/Java_unseen/xuhyacinth_MusicPlayer/src/com/xu/music/player/main/MusicPlayer.java | package com.xu.music.player.main;
import com.xu.music.player.config.Reading;
import com.xu.music.player.config.SongChoiceWindow;
import com.xu.music.player.entity.PlayerEntity;
import com.xu.music.player.lyric.LoadLocalLyric;
import com.xu.music.player.modle.Controller;
import com.xu.music.player.modle.ControllerServer;
import com.xu.music.player.player.Player;
import com.xu.music.player.player.XMusic;
import com.xu.music.player.system.Constant;
import com.xu.music.player.tray.MusicPlayerTray;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.*;
import org.eclipse.wb.swt.SWTResourceManager;
import java.awt.*;
import java.util.LinkedList;
import java.util.Random;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
/**
* Java MusicPlayer 观察者
*
* @Author: hyacinth
* @ClassName: LyricPlayer
* @Description: TODO
* @Date: 2020年5月18日22:21:13
* @Copyright: hyacinth
*/
public class MusicPlayer {
public static boolean playing = true;// 播放按钮
private static Player player = null;//播放器
private static int merchant = 0;
private static int remainder = 0;
private static String format = "";
protected Shell shell;
private Display display;
private Tray tray;// 播放器托盘
private Table lists;
private Table lyrics;
private Composite top;
private Composite foot; // 频谱面板
private ProgressBar progress; // 进度条
private Label ttime;
private int clickX, clickY;//界面移动
private Label rtime;
private boolean choise = true;// 双击播放
private Label start;
private ControllerServer server = new ControllerServer(); // 歌词及频谱
private boolean click = false;//界面移动
/**
* Launch the application.
*
* @param args
*/
public static void main(String[] args) {
try {
MusicPlayer window = new MusicPlayer();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
private static String format(int time) {
merchant = time / 60;
remainder = time % 60;
if (time < 10) {
format = "00:0" + time;
} else if (time < 60) {
format = "00:" + time;
} else {
if (merchant < 10 && remainder < 10) {
format = "0" + merchant + ":0" + remainder;
} else if (merchant < 10 && remainder < 60) {
format = "0" + merchant + ":" + remainder;
} else if (merchant >= 10 && remainder < 10) {
format = merchant + ":0" + remainder;
} else if (merchant >= 10 && remainder < 60) {
format = merchant + ":0" + remainder;
}
}
return format;
}
public static void JVMinfo() {
long vmFree;
long vmUse;
long vmTotal;
long vmMax;
int byteToMb = 1024;
Runtime rt = Runtime.getRuntime();
vmTotal = rt.totalMemory() / byteToMb;
vmFree = rt.freeMemory() / byteToMb;
vmMax = rt.maxMemory() / byteToMb;
vmUse = vmTotal - vmFree;
System.out.println("JVM 已用内存为:" + vmUse + "\tKB");
System.out.println("JVM 空闲内存为:" + vmFree + "\tKB");
System.out.println("JVM 可用内存为:" + vmTotal + "\tKB");
System.out.println("JVM 最大内存为:" + vmMax + "\tKB");
System.gc();
}
/**
* Open the window.
*/
public void open() {
display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
* Create contents of the window.
*/
protected void createContents() {
shell = new Shell(SWT.NONE);
shell.setImage(SWTResourceManager.getImage(MusicPlayer.class, "/com/xu/music/player/image/main.png"));
shell.setSize(new Point(1000, 645));
shell.setSize(900, 486);
shell.setText("MusicPlayer");
shell.setLocation((display.getClientArea().width - shell.getSize().x) / 2,
(display.getClientArea().height - shell.getSize().y) / 2);
shell.setLayout(new FillLayout(SWT.HORIZONTAL));
shell.setBackgroundMode(SWT.INHERIT_DEFAULT);
player = XMusic.player();
// 托盘引入
tray = display.getSystemTray();
MusicPlayerTray trayutil = new MusicPlayerTray(shell, tray);
trayutil.tray();
Composite mpanel = new Composite(shell, SWT.NONE);
mpanel.setBackgroundMode(SWT.INHERIT_FORCE);
mpanel.setLayout(new FillLayout(SWT.HORIZONTAL));
SashForm mform = new SashForm(mpanel, SWT.VERTICAL);
top = new Composite(mform, SWT.NONE);
top.setBackgroundMode(SWT.INHERIT_FORCE);
Label exit = new Label(top, SWT.NONE);
exit.setImage(SWTResourceManager.getImage(MusicPlayer.class, "/com/xu/music/player/image/exit-1.png"));
exit.setBounds(845, 10, 32, 32);
Label mini = new Label(top, SWT.NONE);
mini.setImage(SWTResourceManager.getImage(MusicPlayer.class, "/com/xu/music/player/image/mini-1.png"));
mini.setBounds(798, 10, 32, 32);
Combo combo = new Combo(top, SWT.NONE);
combo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
combo.clearSelection();
}
});
combo.addModifyListener(arg0 -> {
//List<APISearchTipsEntity> songs = Search.search(combo.getText(),"API");
//for (APISearchTipsEntity song:songs) {
// combo.add(song.getFilename());
//}
//combo.setListVisible(true);
combo.clearSelection();
for (int i = 0; i < Constant.MUSIC_PLAYER_SONGS_LIST.size(); i++) {
if (Constant.MUSIC_PLAYER_SONGS_LIST.get(i).contains(combo.getText())) {
combo.add(Constant.MUSIC_PLAYER_SONGS_LIST.get(i).split(Constant.MUSIC_PLAYER_SYSTEM_SPLIT)[1]);
}
}
combo.setListVisible(true);
});
combo.setBounds(283, 21, 330, 25);
combo.setVisible(false);
Composite center = new Composite(mform, SWT.NONE);
center.setBackgroundMode(SWT.INHERIT_FORCE);
center.setLayout(new FillLayout(SWT.HORIZONTAL));
SashForm cform = new SashForm(center, SWT.NONE);
Composite lpanel = new Composite(cform, SWT.NONE);
lpanel.setBackgroundMode(SWT.INHERIT_FORCE);
lpanel.setLayout(new FillLayout(SWT.HORIZONTAL));
lists = new Table(lpanel, SWT.FULL_SELECTION);
lists.setHeaderVisible(true);
TableColumn tableColumn = new TableColumn(lists, SWT.NONE);
tableColumn.setWidth(41);
tableColumn.setText("序号");
TableColumn tableColumn_1 = new TableColumn(lists, SWT.NONE);
tableColumn_1.setWidth(117);
tableColumn_1.setText("歌曲");
Composite rpanel = new Composite(cform, SWT.NONE);
rpanel.setBackgroundMode(SWT.INHERIT_FORCE);
rpanel.setLayout(new FillLayout(SWT.HORIZONTAL));
lyrics = new Table(rpanel, SWT.NONE);
TableColumn tableColumn_2 = new TableColumn(lyrics, SWT.CENTER);
tableColumn_2.setText("歌词");
TableColumn tableColumn_3 = new TableColumn(lyrics, SWT.CENTER);
tableColumn_3.setWidth(738);
tableColumn_3.setText("歌词");
foot = new Composite(mform, SWT.NONE);
foot.setBackgroundMode(SWT.INHERIT_FORCE);
Label prev = new Label(foot, SWT.NONE);
prev.setImage(SWTResourceManager.getImage(MusicPlayer.class, "/com/xu/music/player/image/lastsong-1.png"));
prev.setBounds(33, 18, 32, 32);
Label next = new Label(foot, SWT.NONE);
next.setImage(SWTResourceManager.getImage(MusicPlayer.class, "/com/xu/music/player/image/nextsong-1.png"));
next.setBounds(165, 18, 32, 32);
start = new Label(foot, SWT.NONE);
start.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
playing = Constant.MUSIC_PLAYER_PLAYING_STATE;
if (playing && !XMusic.isPlaying()) {
//TODO:
start.setImage(SWTResourceManager.getImage(MusicPlayer.class, "/com/xu/music/player/image/start.png"));
playing = false;
} else {
//TODO:
playing = true;
start.setImage(SWTResourceManager.getImage(MusicPlayer.class, "/com/xu/music/player/image/stop.png"));
}
}
});
start.setImage(SWTResourceManager.getImage(MusicPlayer.class, "/com/xu/music/player/image/stop.png"));
start.setBounds(98, 18, 32, 32);
progress = new ProgressBar(foot, SWT.NONE);
progress.setEnabled(false);
progress.setBounds(238, 25, 610, 17);
progress.setMaximum(100);//设置进度条的最大长度
progress.setSelection(0);
progress.setMinimum(0);//设置进度的条最小程度
ttime = new Label(foot, SWT.NONE);
ttime.setFont(SWTResourceManager.getFont("Consolas", 9, SWT.NORMAL));
ttime.setEnabled(false);
ttime.setBounds(238, 4, 73, 20);
rtime = new Label(foot, SWT.RIGHT);
rtime.setFont(SWTResourceManager.getFont("Consolas", 9, SWT.NORMAL));
rtime.setEnabled(false);
rtime.setBounds(775, 4, 73, 20);
mform.setWeights(new int[]{1, 5, 1});
cform.setWeights(new int[]{156, 728});
//界面移动
top.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
click = true;
clickX = e.x;
clickY = e.y;
}
@Override
public void mouseUp(MouseEvent e) {
click = false;
}
});
top.addMouseMoveListener(arg0 -> {//当鼠标按下的时候执行这条语句
if (click) {
shell.setLocation(shell.getLocation().x - clickX + arg0.x, shell.getLocation().y - clickY + arg0.y);
}
});
// 缩小
mini.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
mini.setImage(SWTResourceManager.getImage(MusicPlayer.class, "/com/xu/music/player/image/mini-2.png"));
}
@Override
public void mouseUp(MouseEvent e) {
mini.setImage(SWTResourceManager.getImage(MusicPlayer.class, "/com/xu/music/player/image/mini-1.png"));
shell.setMinimized(true);
}
});
mini.addMouseTrackListener(new MouseTrackAdapter() {
@Override
public void mouseExit(MouseEvent e) {
mini.setImage(SWTResourceManager.getImage(MusicPlayer.class, "/com/xu/music/player/image/mini-1.png"));
}
@Override
public void mouseHover(MouseEvent e) {
mini.setImage(SWTResourceManager.getImage(MusicPlayer.class, "/com/xu/music/player/image/mini-2.png"));
mini.setToolTipText("最小化");
}
});
//退出
exit.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
exit.setImage(SWTResourceManager.getImage(MusicPlayer.class, "/com/xu/music/player/image/exit-2.png"));
}
@Override
public void mouseUp(MouseEvent e) {
exit.setImage(SWTResourceManager.getImage(MusicPlayer.class, "/com/xu/music/player/image/exit-1.png"));
exitMusicPlayer();
}
});
exit.addMouseTrackListener(new MouseTrackAdapter() {
@Override
public void mouseExit(MouseEvent e) {
exit.setImage(SWTResourceManager.getImage(MusicPlayer.class, "/com/xu/music/player/image/exit-1.png"));
}
@Override
public void mouseHover(MouseEvent e) {
exit.setImage(SWTResourceManager.getImage(MusicPlayer.class, "/com/xu/music/player/image/exit-2.png"));
exit.setToolTipText("退出");
}
});
//双击播放
lists.addMouseListener(new MouseAdapter() {
@Override
public void mouseDoubleClick(MouseEvent e) {
choise = true;
}
});
lists.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (choise) {
TableItem[] items = lists.getSelection();
int index = Integer.parseInt(items[0].getText(0).trim());
changePlayingSong(index - 1, 1);//下一曲
}
}
});
//上一曲
prev.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
prev.setImage(SWTResourceManager.getImage(MusicPlayer.class, "/com/xu/music/player/image/lastsong-2.png"));
}
@Override
public void mouseUp(MouseEvent e) {
changePlayingSong(-1, 0);//上一曲
prev.setImage(SWTResourceManager.getImage(MusicPlayer.class, "/com/xu/music/player/image/lastsong-1.png"));
}
});
//下一曲
next.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
next.setImage(SWTResourceManager.getImage(MusicPlayer.class, "/com/xu/music/player/image/nextsong-2.png"));
}
@Override
public void mouseUp(MouseEvent e) {
changePlayingSong(-1, 1);//下一曲
next.setImage(SWTResourceManager.getImage(MusicPlayer.class, "/com/xu/music/player/image/nextsong-1.png"));
}
});
foot.addControlListener(new ControlAdapter() {
@Override
public void controlResized(ControlEvent e) {
mform.setWeights(new int[]{1, 5, 1});
cform.setWeights(new int[]{156, 728});
}
});
foot.addMouseListener(new MouseAdapter() {
@Override
public void mouseDoubleClick(MouseEvent e) {
Color color = Constant.MUSIC_PLAYER_COLORS.get(new Random().nextInt(Constant.MUSIC_PLAYER_COLORS.size()));
if (color != Constant.SPECTRUM_BACKGROUND_COLOR) {
Constant.SPECTRUM_FOREGROUND_COLOR = color;
}
}
});
mform.addControlListener(new ControlAdapter() {
@Override
public void controlResized(ControlEvent e) {
mform.setWeights(new int[]{1, 5, 1});
cform.setWeights(new int[]{156, 728});
}
});
lpanel.addControlListener(new ControlAdapter() {
@Override
public void controlResized(ControlEvent e) {
mform.setWeights(new int[]{1, 5, 1});
cform.setWeights(new int[]{156, 728});
}
});
rpanel.addControlListener(new ControlAdapter() {
@Override
public void controlResized(ControlEvent e) {
mform.setWeights(new int[]{1, 5, 1});
cform.setWeights(new int[]{156, 728});
}
});
cform.addControlListener(new ControlAdapter() {
@Override
public void controlResized(ControlEvent e) {
mform.setWeights(new int[]{1, 5, 1});
cform.setWeights(new int[]{156, 728});
}
});
initMusicPlayer(shell, lists);
System.gc();
}
/**
* Java MusicPlayer 初始化音乐播放器
*
* @param shell
* @param table
* @return void
* @Author: hyacinth
* @Title: initMusicPlayer
* @Description: TODO
* @date: 2019年12月26日 下午7:20:00
*/
public void initMusicPlayer(Shell shell, Table table) {
SongChoiceWindow choice = new SongChoiceWindow();
new Reading().read();
if (Constant.MUSIC_PLAYER_SONGS_LIST == null || Constant.MUSIC_PLAYER_SONGS_LIST.size() <= 0) {
Toolkit.getDefaultToolkit().beep();
choice.openChoiseWindows(shell);
}
updatePlayerSongLists(Constant.MUSIC_PLAYER_SONGS_LIST, table);
readMusicPlayerPlayingSong();
Constant.MUSIC_PLAYER_COLORS.add(Color.BLACK);
Constant.MUSIC_PLAYER_COLORS.add(Color.BLUE);
Constant.MUSIC_PLAYER_COLORS.add(Color.CYAN);
Constant.MUSIC_PLAYER_COLORS.add(Color.DARK_GRAY);
Constant.MUSIC_PLAYER_COLORS.add(Color.GRAY);
Constant.MUSIC_PLAYER_COLORS.add(Color.GREEN);
Constant.MUSIC_PLAYER_COLORS.add(Color.LIGHT_GRAY);
Constant.MUSIC_PLAYER_COLORS.add(Color.MAGENTA);
Constant.MUSIC_PLAYER_COLORS.add(Color.ORANGE);
Constant.MUSIC_PLAYER_COLORS.add(Color.PINK);
Constant.MUSIC_PLAYER_COLORS.add(Color.RED);
Constant.MUSIC_PLAYER_COLORS.add(Color.WHITE);
Constant.MUSIC_PLAYER_COLORS.add(Color.YELLOW);
}
/**
* Java MusicPlayer 更新播放歌曲列表
*
* @param lists
* @param table
* @return void
* @Author: hyacinth
* @Title: updatePlayerSongLists
* @Description: TODO
* @date: 2019年12月26日 下午7:20:33
*/
private void updatePlayerSongLists(LinkedList<String> lists, Table table) {
table.removeAll();
TableItem item;
for (int i = 0; i < lists.size(); i++) {
item = new TableItem(table, SWT.NONE);
item.setText(new String[]{"" + (i + 1), lists.get(i).split(Constant.MUSIC_PLAYER_SYSTEM_SPLIT)[1]});
}
}
/**
* Java MusicPlayer 更新播放歌曲列表
*
* @param table
* @return void
* @Author: hyacinth
* @Title: markSongsLists
* @Description: TODO
* @date: 2019年12月31日 下午8:20:33
*/
public void markSongsLists(Table table, int index) {
TableItem[] items = table.getItems();
for (int i = 0, len = items.length; i < len; i++) {
if (index == i) {
items[i].setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY));
} else {
items[i].setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
}
}
table.setTopIndex(index);
}
/**
* Java MusicPlayer 改变播放歌曲
* <table border="1" cellpadding="10">
* <tr><td colspan="2" align="center">changePlayingSong</td></tr>
* <tr><th align="center">Mode 输入参数</th><th align="center">参数解释</th></tr>
* <tr><td align="left">0</td><td align="left">上一曲</td></tr>
* <tr><td align="left">1</td><td align="left">下一曲</td></tr>
*
* @param index 歌曲索引
* @param mode 切歌模式(上一曲/下一曲)
* @return void
* @Author: hyacinth
* @Title: changePlayingSong
* @Description: TODO
* @date: 2019年12月26日 下午7:33:36
*/
public void changePlayingSong(int index, int mode) {
System.out.println(Constant.PLAYING_SONG_INDEX + "\t" + Constant.MUSIC_PLAYER_SONGS_LIST.get(Constant.PLAYING_SONG_INDEX));
Constant.PLAYING_SONG_INDEX = index == -1 ? Constant.PLAYING_SONG_INDEX : index;
Constant.PLAYING_SONG_NAME = Constant.MUSIC_PLAYER_SONGS_LIST.get(Constant.PLAYING_SONG_INDEX);
if (Constant.MUSIC_PLAYER_SONGS_LIST.size() <= 0) {
Toolkit.getDefaultToolkit().beep();
MessageBox message = new MessageBox(shell, SWT.YES | SWT.ICON_WARNING | SWT.NO);
message.setText("提示");
message.setMessage("未发现歌曲,现在添加歌曲?");
if (message.open() == SWT.YES) {
initMusicPlayer(shell, lists);
} else {
Toolkit.getDefaultToolkit().beep();
message = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR);
message.setText("提示");
message.setMessage("你将不能播放歌曲。");
message.open();
}
}
player.load(Constant.PLAYING_SONG_NAME.split(Constant.MUSIC_PLAYER_SYSTEM_SPLIT)[0]);
try {
player.start();
} catch (Exception e1) {
e1.printStackTrace();
}
Constant.MUSIC_PLAYER_PLAYING_STATE = true;
updatePlayerSongListsColor(lists, Constant.PLAYING_SONG_INDEX);
if (mode == 0) {//上一曲
if (Constant.PLAYING_SONG_INDEX <= 0) {
Constant.PLAYING_SONG_INDEX = Constant.MUSIC_PLAYER_SONGS_LIST.size();
} else {
Constant.PLAYING_SONG_INDEX--;
}
} else {//下一曲
if (Constant.PLAYING_SONG_INDEX >= Constant.MUSIC_PLAYER_SONGS_LIST.size()) {
Constant.PLAYING_SONG_INDEX = 0;
} else {
Constant.PLAYING_SONG_INDEX++;
}
}
}
/**
* Java MusicPlayer 改变选中歌曲的颜色
*
* @param table
* @param index
* @return void
* @Author: hyacinth
* @Title: updatePlayerSongListsColor
* @Description: TODO
* @date: 2019年12月26日 下午7:40:10
*/
private void updatePlayerSongListsColor(Table table, int index) {
start.setImage(SWTResourceManager.getImage(MusicPlayer.class, "/com/xu/music/player/image/start.png"));
Constant.PLAYING_SONG_HAVE_LYRIC = false;
Constant.PLAYING_SONG_LENGTH = Integer.parseInt(Constant.PLAYING_SONG_NAME.split(Constant.MUSIC_PLAYER_SYSTEM_SPLIT)[3]);
ttime.setText(format(Constant.PLAYING_SONG_LENGTH));
TableItem[] items = table.getItems();
for (int i = 0; i < items.length; i++) {
if (index == i) {
items[i].setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY));
} else {
items[i].setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
}
}
if (index <= 7) {
table.setTopIndex(index);
} else {
table.setTopIndex(index - 7);
}
if ("Y".equalsIgnoreCase(Constant.MUSIC_PLAYER_SONGS_LIST.get(Constant.PLAYING_SONG_INDEX).split(Constant.MUSIC_PLAYER_SYSTEM_SPLIT)[4])) {
Constant.PLAYING_SONG_HAVE_LYRIC = true;
LoadLocalLyric lyric = new LoadLocalLyric();
String path = Constant.MUSIC_PLAYER_SONGS_LIST.get(Constant.PLAYING_SONG_INDEX).split(Constant.MUSIC_PLAYER_SYSTEM_SPLIT)[0];
path = path.substring(0, path.lastIndexOf(".")) + ".lrc";
lyric.lyric(path);
lyrics.removeAll();
if (Constant.PLAYING_SONG_LYRIC != null && Constant.PLAYING_SONG_LYRIC.size() > 0) {
TableItem item;
for (int i = 0, len = Constant.PLAYING_SONG_LYRIC.size() + 8; i < len; i++) {
item = new TableItem(lyrics, SWT.NONE);
if (i < len - 8) {
item.setText(new String[]{"", Constant.PLAYING_SONG_LYRIC.get(i).split(Constant.MUSIC_PLAYER_SYSTEM_SPLIT)[1]});
}
}
PlayerEntity.setBar(progress);
PlayerEntity.setText(rtime);
PlayerEntity.setSong(Constant.PLAYING_SONG_NAME);
PlayerEntity.setTable(lyrics);
}
PlayerEntity.setSpectrum(foot);
server.endLyricPlayer(new Controller());
server.startLyricPlayer(new Controller(), null);
}
setMusicPlayerPlayingSong(index + "");
JVMinfo();
}
/**
* Java MusicPlayer 退出音乐播放器
*
* @return void
* @Author: hyacinth
* @Title: exitMusicPlayer
* @Description: TODO
* @date: 2019年12月26日 下午7:57:12
*/
private void exitMusicPlayer() {
tray.dispose();
System.exit(0);
player.stop();
shell.dispose();
}
/**
* Java MusicPlayer 将正在播放的歌曲存在注册表中
*
* @param index
* @return void
* @Author: hyacinth
* @Title: setMusicPlayerPlayingSong
* @Description: TODO
* @date: 2019年12月29日 下午2:57:30
*/
private void setMusicPlayerPlayingSong(String index) {
Preferences preferences = Preferences.userNodeForPackage(MusicPlayer.class);
if (preferences.get("MusicPlayer", null) == null) {
preferences.put("MusicPlayer", index);
} else {
preferences.put("MusicPlayer", index);
}
try {
preferences.flush();
} catch (BackingStoreException e) {
e.printStackTrace();
}
}
/**
* Java MusicPlayer 读取上次播放器退出前播放的歌曲
*
* @return void
* @Author: hyacinth
* @Title: readMusicPlayerPlayingSong
* @Description: TODO
* @date: 2019年12月29日 下午2:58:24
*/
private void readMusicPlayerPlayingSong() {
//Preferences preferences = Preferences.userNodeForPackage(MusicPlayer.class);
//String index = preferences.get("MusicPlayer", null);
//next_song(Integer.parseInt(index));
}
/**
* Java MusicPlayer 暂停播放(未实现)
*
* @return void
* @Author: hyacinth
* @Title: stopMusicPlayer
* @Description: TODO
* @date: 2019年12月26日 下午7:47:41
*/
public void stopMusicPlayer() {
try {
player.end();
} catch (Exception e) {
e.printStackTrace();
}
Constant.MUSIC_PLAYER_PLAYING_STATE = false;
start.setImage(SWTResourceManager.getImage(MusicPlayer.class, "/com/xu/music/player/image/stop.png"));
updatePlayerSongListsColor(lists, Constant.PLAYING_SONG_INDEX);
}
}
| 26,696 | Java | .java | xuhyacinth/MusicPlayer | 9 | 0 | 0 | 2020-12-13T04:23:25Z | 2022-03-15T03:58:12Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.