use of com.codename1.ui.util.xml.Data in project CodenameOne by codenameone.
the class EditableResources method save.
/**
* Allows us to store a modified resource file
*/
public void save(OutputStream out) throws IOException {
if (overrideFile != null) {
overrideResource.save(new FileOutputStream(overrideFile));
}
// disable override for the duration of the save so stuff from the override doesn't
// get into the main resource file
File overrideFileBackup = overrideFile;
EditableResources overrideResourceBackup = overrideResource;
overrideResource = null;
overrideFile = null;
try {
DataOutputStream output = new DataOutputStream(out);
String[] resourceNames = getResourceNames();
keyOffset = 0;
if (currentPassword != null) {
output.writeShort(resourceNames.length + 2);
output.writeByte(MAGIC_PASSWORD);
output.writeUTF("" + ((char) encode('l')) + ((char) encode('w')));
output.writeByte(encode(MAGIC_HEADER & 0xff));
} else {
output.writeShort(resourceNames.length + 1);
// write the header of the resource file
output.writeByte(MAGIC_HEADER);
}
output.writeUTF("");
// the size of the header
output.writeShort(6);
output.writeShort(MAJOR_VERSION);
output.writeShort(MINOR_VERSION);
// currently resource file meta-data isn't supported
output.writeShort(0);
for (int iter = 0; iter < resourceNames.length; iter++) {
// write the magic number
byte magic = getResourceType(resourceNames[iter]);
switch(magic) {
case MAGIC_TIMELINE:
case MAGIC_ANIMATION_LEGACY:
case MAGIC_IMAGE_LEGACY:
case MAGIC_INDEXED_IMAGE_LEGACY:
magic = MAGIC_IMAGE;
break;
case MAGIC_THEME_LEGACY:
magic = MAGIC_THEME;
break;
case MAGIC_FONT_LEGACY:
magic = MAGIC_FONT;
break;
}
if (currentPassword != null) {
output.writeByte(encode(magic & 0xff));
char[] chars = resourceNames[iter].toCharArray();
for (int i = 0; i < chars.length; i++) {
chars[i] = (char) encode(chars[i] & 0xffff);
}
output.writeUTF(new String(chars));
} else {
output.writeByte(magic);
output.writeUTF(resourceNames[iter]);
}
switch(magic) {
case MAGIC_IMAGE:
Object o = getResourceObject(resourceNames[iter]);
if (!(o instanceof MultiImage)) {
o = null;
}
saveImage(output, getImage(resourceNames[iter]), (MultiImage) o, BufferedImage.TYPE_INT_ARGB);
continue;
case MAGIC_THEME:
saveTheme(output, getTheme(resourceNames[iter]), magic == MAGIC_THEME_LEGACY);
continue;
case MAGIC_FONT:
saveFont(output, false, resourceNames[iter]);
continue;
case MAGIC_DATA:
{
InputStream i = getData(resourceNames[iter]);
ByteArrayOutputStream outArray = new ByteArrayOutputStream();
int val = i.read();
while (val != -1) {
outArray.write(val);
val = i.read();
}
byte[] data = outArray.toByteArray();
output.writeInt(data.length);
output.write(data);
continue;
}
case MAGIC_UI:
{
InputStream i = getUi(resourceNames[iter]);
ByteArrayOutputStream outArray = new ByteArrayOutputStream();
int val = i.read();
while (val != -1) {
outArray.write(val);
val = i.read();
}
byte[] data = outArray.toByteArray();
output.writeInt(data.length);
output.write(data);
continue;
}
case MAGIC_L10N:
// we are getting the theme which allows us to acces the l10n data
saveL10N(output, getTheme(resourceNames[iter]));
continue;
default:
throw new IOException("Corrupt theme file unrecognized magic number: " + Integer.toHexString(magic & 0xff));
}
}
modified = false;
updateModified();
undoQueue.clear();
redoQueue.clear();
} finally {
overrideFile = overrideFileBackup;
overrideResource = overrideResourceBackup;
}
}
use of com.codename1.ui.util.xml.Data in project CodenameOne by codenameone.
the class L10nEditor method importResourceActionPerformed.
// GEN-LAST:event_exportResourceActionPerformed
private void importResourceActionPerformed(java.awt.event.ActionEvent evt) {
// GEN-FIRST:event_importResourceActionPerformed
final String locale = (String) locales.getSelectedItem();
int val = JOptionPane.showConfirmDialog(this, "This will overwrite existing values for " + locale + "\nAre you sure?", "Import", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (val == JOptionPane.YES_OPTION) {
File[] files = ResourceEditorView.showOpenFileChooser("Properties, XML, CSV", "prop", "properties", "l10n", "locale", "xml", "csv");
if (files != null) {
FileInputStream f = null;
try {
f = new FileInputStream(files[0]);
if (files[0].getName().toLowerCase().endsWith("xml")) {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser saxParser = spf.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setErrorHandler(new ErrorHandler() {
public void warning(SAXParseException exception) throws SAXException {
exception.printStackTrace();
}
public void error(SAXParseException exception) throws SAXException {
exception.printStackTrace();
}
public void fatalError(SAXParseException exception) throws SAXException {
exception.printStackTrace();
}
});
xmlReader.setContentHandler(new ContentHandler() {
private String currentName;
private StringBuilder chars = new StringBuilder();
@Override
public void setDocumentLocator(Locator locator) {
}
@Override
public void startDocument() throws SAXException {
}
@Override
public void endDocument() throws SAXException {
}
@Override
public void startPrefixMapping(String prefix, String uri) throws SAXException {
}
@Override
public void endPrefixMapping(String prefix) throws SAXException {
}
@Override
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
if ("string".equals(localName) || "string".equals(qName)) {
currentName = atts.getValue("name");
chars.setLength(0);
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if ("string".equals(localName) || "string".equals(qName)) {
String str = chars.toString();
if (str.startsWith("\"") && str.endsWith("\"")) {
str = str.substring(1);
str = str.substring(0, str.length() - 1);
res.setLocaleProperty(localeName, locale, currentName, str);
return;
}
str = str.replace("\\'", "'");
res.setLocaleProperty(localeName, locale, currentName, str);
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
chars.append(ch, start, length);
}
@Override
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
}
@Override
public void processingInstruction(String target, String data) throws SAXException {
}
@Override
public void skippedEntity(String name) throws SAXException {
}
});
xmlReader.parse(new InputSource(new InputStreamReader(f, "UTF-8")));
} else {
if (files[0].getName().toLowerCase().endsWith("csv")) {
CSVParserOptions po = new CSVParserOptions(this);
if (po.isCanceled()) {
f.close();
return;
}
CSVParser p = new CSVParser(po.getDelimiter());
String[][] data = p.parse(new InputStreamReader(f, po.getEncoding()));
for (int iter = 1; iter < data.length; iter++) {
if (data[iter].length > 0) {
String key = data[iter][0];
for (int col = 1; col < data[iter].length; col++) {
if (res.getL10N(localeName, data[0][col]) == null) {
res.addLocale(localeName, data[0][col]);
}
res.setLocaleProperty(localeName, data[0][col], key, data[iter][col]);
}
}
}
} else {
Properties prop = new Properties();
prop.load(f);
for (Object key : prop.keySet()) {
res.setLocaleProperty(localeName, locale, (String) key, prop.getProperty((String) key));
}
}
}
f.close();
initLocaleList();
for (Object localeObj : localeList) {
Hashtable current = res.getL10N(localeName, (String) localeObj);
for (Object key : current.keySet()) {
if (!keys.contains(key)) {
keys.add(key);
}
}
}
Collections.sort(keys);
initTable();
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "Error: " + ex, "Error Occured", JOptionPane.ERROR_MESSAGE);
}
}
}
}
use of com.codename1.ui.util.xml.Data in project CodenameOne by codenameone.
the class ResourceEditorView method importResourceStream.
public void importResourceStream(InputStream is) throws IOException {
EditableResources r = new EditableResources();
r.openFile(is);
checkDuplicateResourcesLoop(r, loadedResources.getThemeResourceNames(), r.getThemeResourceNames(), "Rename Theme", "Theme ");
// load all the themes so rename will work properly on images and won't conflict
for (String t : r.getThemeResourceNames()) {
r.getTheme(t);
}
checkDuplicateResourcesLoop(r, loadedResources.getImageResourceNames(), r.getImageResourceNames(), "Rename Image", "Image ");
checkDuplicateResourcesLoop(r, loadedResources.getL10NResourceNames(), r.getL10NResourceNames(), "Rename Localization", "Localization ");
checkDuplicateResourcesLoop(r, loadedResources.getDataResourceNames(), r.getDataResourceNames(), "Rename Data", "Data ");
checkDuplicateResourcesLoop(r, loadedResources.getUIResourceNames(), r.getUIResourceNames(), "Rename GUI", "GUI ");
checkDuplicateResourcesLoop(r, loadedResources.getFontResourceNames(), r.getFontResourceNames(), "Rename Font", "Font ");
for (String s : r.getImageResourceNames()) {
if (r.isMultiImage(s)) {
loadedResources.setMultiImage(s, (EditableResources.MultiImage) r.getResourceObject(s));
} else {
loadedResources.setImage(s, r.getImage(s));
}
}
for (String s : r.getL10NResourceNames()) {
loadedResources.setL10N(s, (Hashtable) r.getResourceObject(s));
}
for (String s : r.getDataResourceNames()) {
loadedResources.setData(s, (byte[]) r.getResourceObject(s));
}
for (String s : r.getUIResourceNames()) {
loadedResources.setUi(s, (byte[]) r.getResourceObject(s));
}
for (String s : r.getFontResourceNames()) {
loadedResources.setFont(s, r.getFont(s));
}
for (String s : r.getThemeResourceNames()) {
loadedResources.setTheme(s, r.getTheme(s));
}
}
use of com.codename1.ui.util.xml.Data in project CodenameOne by codenameone.
the class ResourceEditorApp method importRes.
private static Hashtable importRes(EditableResources res, String file) {
InputStream is = ResourceEditorApp.class.getResourceAsStream("/templates/" + file + ".res");
Hashtable theme = new Hashtable();
if (is != null) {
try {
EditableResources r = new EditableResources();
r.openFile(is);
is.close();
if (r.getThemeResourceNames().length > 0) {
theme = r.getTheme(r.getThemeResourceNames()[0]);
}
ResourceEditorView.checkDuplicateResourcesLoop(r, res.getImageResourceNames(), r.getImageResourceNames(), "Rename Image", "Image ", true, null);
ResourceEditorView.checkDuplicateResourcesLoop(r, res.getL10NResourceNames(), r.getL10NResourceNames(), "Rename Localization", "Localization ", true, null);
ResourceEditorView.checkDuplicateResourcesLoop(r, res.getDataResourceNames(), r.getDataResourceNames(), "Rename Data", "Data ", true, null);
ResourceEditorView.checkDuplicateResourcesLoop(r, res.getUIResourceNames(), r.getUIResourceNames(), "Rename GUI", "GUI ", true, null);
ResourceEditorView.checkDuplicateResourcesLoop(r, res.getFontResourceNames(), r.getFontResourceNames(), "Rename Font", "Font ", true, null);
for (String s : r.getImageResourceNames()) {
if (r.isMultiImage(s)) {
res.setMultiImage(s, (EditableResources.MultiImage) r.getResourceObject(s));
} else {
res.setImage(s, r.getImage(s));
}
}
for (String s : r.getL10NResourceNames()) {
res.setL10N(s, (Hashtable) r.getResourceObject(s));
}
for (String s : r.getDataResourceNames()) {
res.setData(s, (byte[]) r.getResourceObject(s));
}
for (String s : r.getUIResourceNames()) {
res.setUi(s, (byte[]) r.getResourceObject(s));
}
for (String s : r.getFontResourceNames()) {
res.setFont(s, r.getFont(s));
}
} catch (IOException err) {
err.printStackTrace();
}
}
return theme;
}
use of com.codename1.ui.util.xml.Data in project CodenameOne by codenameone.
the class JavaSEPort method createSkinsMenu.
private JMenu createSkinsMenu(final JFrame frm, final JMenu menu) throws MalformedURLException {
JMenu m;
if (menu == null) {
m = new JMenu("Skins");
m.setDoubleBuffered(true);
} else {
m = menu;
m.removeAll();
}
final JMenu skinMenu = m;
Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
String skinNames = pref.get("skins", DEFAULT_SKINS);
if (skinNames != null) {
if (skinNames.length() < DEFAULT_SKINS.length()) {
skinNames = DEFAULT_SKINS;
}
ButtonGroup skinGroup = new ButtonGroup();
StringTokenizer tkn = new StringTokenizer(skinNames, ";");
while (tkn.hasMoreTokens()) {
final String current = tkn.nextToken();
String name = current;
if (current.contains(":")) {
try {
URL u = new URL(current);
File f = new File(u.getFile());
if (!f.exists()) {
continue;
}
name = f.getName();
} catch (Exception e) {
continue;
}
} else {
// remove the old builtin skins from the menu
if (current.startsWith("/") && !current.equals("/iphone3gs.skin")) {
continue;
}
}
String d = System.getProperty("dskin");
JRadioButtonMenuItem i = new JRadioButtonMenuItem(name, name.equals(pref.get("skin", d)));
i.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (netMonitor != null) {
netMonitor.dispose();
netMonitor = null;
}
if (perfMonitor != null) {
perfMonitor.dispose();
perfMonitor = null;
}
Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
pref.putBoolean("desktopSkin", false);
String mainClass = System.getProperty("MainClass");
if (mainClass != null) {
pref.put("skin", current);
deinitializeSync();
frm.dispose();
System.setProperty("reload.simulator", "true");
} else {
loadSkinFile(current, frm);
refreshSkin(frm);
}
}
});
skinGroup.add(i);
skinMenu.add(i);
}
}
JMenuItem dSkin = new JMenuItem("Desktop.skin");
dSkin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (netMonitor != null) {
netMonitor.dispose();
netMonitor = null;
}
if (perfMonitor != null) {
perfMonitor.dispose();
perfMonitor = null;
}
Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
pref.putBoolean("desktopSkin", true);
String mainClass = System.getProperty("MainClass");
if (mainClass != null) {
deinitializeSync();
frm.dispose();
System.setProperty("reload.simulator", "true");
}
}
});
skinMenu.addSeparator();
skinMenu.add(dSkin);
skinMenu.addSeparator();
JMenuItem more = new JMenuItem("More...");
skinMenu.add(more);
more.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final JDialog pleaseWait = new JDialog(frm, false);
pleaseWait.setLocationRelativeTo(frm);
pleaseWait.setTitle("Message");
pleaseWait.setLayout(new BorderLayout());
pleaseWait.add(new JLabel(" Please Wait... "), BorderLayout.CENTER);
pleaseWait.pack();
pleaseWait.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final JDialog d = new JDialog(frm, true);
d.setLocationRelativeTo(frm);
d.setTitle("Skins");
d.setLayout(new BorderLayout());
String userDir = System.getProperty("user.home");
final File skinDir = new File(userDir + "/.codenameone/");
if (!skinDir.exists()) {
skinDir.mkdir();
}
Vector data = new Vector();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
final Document[] doc = new Document[1];
try {
DocumentBuilder db = dbf.newDocumentBuilder();
Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
InputStream is = openSkinsURL();
doc[0] = db.parse(is);
NodeList skins = doc[0].getElementsByTagName("Skin");
for (int i = 0; i < skins.getLength(); i++) {
Node skin = skins.item(i);
NamedNodeMap attr = skin.getAttributes();
String url = attr.getNamedItem("url").getNodeValue();
int ver = 0;
Node n = attr.getNamedItem("version");
if (n != null) {
ver = Integer.parseInt(n.getNodeValue());
}
boolean exists = new File(skinDir.getAbsolutePath() + url).exists();
if (!(exists) || Integer.parseInt(pref.get(url, "0")) < ver) {
Vector row = new Vector();
row.add(new Boolean(false));
row.add(new ImageIcon(new URL(defaultCodenameOneComProtocol + "://www.codenameone.com/OTA" + attr.getNamedItem("icon").getNodeValue())));
row.add(attr.getNamedItem("name").getNodeValue());
if (exists) {
row.add("Update");
} else {
row.add("New");
}
data.add(row);
}
}
} catch (Exception ex) {
Logger.getLogger(JavaSEPort.class.getName()).log(Level.SEVERE, null, ex);
}
if (data.size() == 0) {
pleaseWait.setVisible(false);
JOptionPane.showMessageDialog(frm, "No New Skins to Install");
return;
}
Vector cols = new Vector();
cols.add("Install");
cols.add("Icon");
cols.add("Name");
cols.add("");
final DefaultTableModel tableModel = new DefaultTableModel(data, cols) {
@Override
public boolean isCellEditable(int row, int column) {
return column == 0;
}
};
JTable skinsTable = new JTable(tableModel) {
@Override
public Class<?> getColumnClass(int column) {
if (column == 0) {
return Boolean.class;
}
if (column == 1) {
return Icon.class;
}
return super.getColumnClass(column);
}
};
skinsTable.setRowHeight(112);
skinsTable.getTableHeader().setReorderingAllowed(false);
d.add(new JScrollPane(skinsTable), BorderLayout.CENTER);
JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));
JButton download = new JButton("Download");
download.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final Vector toDowload = new Vector();
NodeList skins = doc[0].getElementsByTagName("Skin");
for (int i = 0; i < tableModel.getRowCount(); i++) {
if (((Boolean) tableModel.getValueAt(i, 0)).booleanValue()) {
Node skin;
for (int j = 0; j < skins.getLength(); j++) {
skin = skins.item(j);
NamedNodeMap attr = skin.getAttributes();
if (attr.getNamedItem("name").getNodeValue().equals(tableModel.getValueAt(i, 2))) {
String url = attr.getNamedItem("url").getNodeValue();
String[] data = new String[2];
data[0] = defaultCodenameOneComProtocol + "://www.codenameone.com/OTA" + url;
data[1] = attr.getNamedItem("version").getNodeValue();
toDowload.add(data);
break;
}
}
}
}
if (toDowload.size() > 0) {
final JDialog downloadMessage = new JDialog(d, true);
downloadMessage.setTitle("Downloading");
downloadMessage.setLayout(new FlowLayout());
downloadMessage.setLocationRelativeTo(d);
final JLabel details = new JLabel("<br><br>Details");
downloadMessage.add(details);
final JLabel progress = new JLabel("Progress<br><br>");
downloadMessage.add(progress);
new Thread() {
@Override
public void run() {
for (Iterator it = toDowload.iterator(); it.hasNext(); ) {
String[] data = (String[]) it.next();
String url = data[0];
details.setText(url.substring(url.lastIndexOf("/")));
details.repaint();
progress.setText("");
progress.repaint();
try {
File skin = downloadSkin(skinDir, url, data[1], progress);
if (skin.exists()) {
addSkinName(skin.toURI().toString());
}
} catch (Exception e) {
}
}
downloadMessage.setVisible(false);
d.setVisible(false);
try {
createSkinsMenu(frm, skinMenu);
} catch (MalformedURLException ex) {
Logger.getLogger(JavaSEPort.class.getName()).log(Level.SEVERE, null, ex);
}
}
}.start();
downloadMessage.pack();
downloadMessage.setSize(200, 70);
downloadMessage.setVisible(true);
} else {
JOptionPane.showMessageDialog(d, "Choose a Skin to Download");
}
}
});
p.add(download);
d.add(p, BorderLayout.SOUTH);
d.pack();
pleaseWait.dispose();
d.setVisible(true);
}
});
}
});
skinMenu.addSeparator();
JMenuItem addSkin = new JMenuItem("Add New...");
skinMenu.add(addSkin);
addSkin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
FileDialog picker = new FileDialog(frm, "Add Skin");
picker.setMode(FileDialog.LOAD);
picker.setFilenameFilter(new FilenameFilter() {
public boolean accept(File file, String string) {
return string.endsWith(".skin");
}
});
picker.setModal(true);
picker.setVisible(true);
String file = picker.getFile();
if (file != null) {
if (netMonitor != null) {
netMonitor.dispose();
netMonitor = null;
}
if (perfMonitor != null) {
perfMonitor.dispose();
perfMonitor = null;
}
String mainClass = System.getProperty("MainClass");
if (mainClass != null) {
Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
pref.put("skin", picker.getDirectory() + File.separator + file);
deinitializeSync();
frm.dispose();
System.setProperty("reload.simulator", "true");
} else {
loadSkinFile(picker.getDirectory() + File.separator + file, frm);
refreshSkin(frm);
}
}
}
});
skinMenu.addSeparator();
JMenuItem reset = new JMenuItem("Reset Skins");
skinMenu.add(reset);
reset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (JOptionPane.showConfirmDialog(frm, "Are you sure you want to reset skins to default?", "Clean Storage", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
pref.put("skins", DEFAULT_SKINS);
String userDir = System.getProperty("user.home");
final File skinDir = new File(userDir + "/.codenameone/");
if (skinDir.exists()) {
File[] childs = skinDir.listFiles();
for (int i = 0; i < childs.length; i++) {
File child = childs[i];
if (child.getName().endsWith(".skin")) {
child.delete();
}
}
}
if (netMonitor != null) {
netMonitor.dispose();
netMonitor = null;
}
if (perfMonitor != null) {
perfMonitor.dispose();
perfMonitor = null;
}
String mainClass = System.getProperty("MainClass");
if (mainClass != null) {
pref.put("skin", "/iphone3gs.skin");
deinitializeSync();
frm.dispose();
System.setProperty("reload.simulator", "true");
} else {
loadSkinFile("/iphone3gs.skin", frm);
refreshSkin(frm);
}
}
}
});
return skinMenu;
}
Aggregations