diff --git a/resources/META-INF/plugin.xml b/resources/META-INF/plugin.xml index cbd0aa4..011f090 100644 --- a/resources/META-INF/plugin.xml +++ b/resources/META-INF/plugin.xml @@ -1,7 +1,7 @@ com.hr.dimenify Dimenify - 3.2 + 3.3 Anvith Bhat v3.3
+ - Fixed a long standing bug in single dimen conversion. + - Prettier xml v3.2
- Fixed a message formatter bug causing floated strings to be prettified with comma. diff --git a/src/com/hr/dimenify/action/AbstractDimenAction.java b/src/com/hr/dimenify/action/AbstractDimenAction.java index 9e1aefb..456de3f 100644 --- a/src/com/hr/dimenify/action/AbstractDimenAction.java +++ b/src/com/hr/dimenify/action/AbstractDimenAction.java @@ -14,10 +14,14 @@ import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; +import com.intellij.psi.xml.XmlFile; +import com.intellij.psi.xml.XmlTag; import javax.swing.*; -import java.util.ArrayList; -import java.util.Locale; +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.text.MessageFormat; +import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import static com.hr.dimenify.util.Constants.*; @@ -26,9 +30,10 @@ public abstract class AbstractDimenAction extends AnAction { protected ArrayList data; protected Project project; - protected String values[]; protected AtomicInteger fileCreationCount = new AtomicInteger(0); protected int currentBucketIndex; + protected PsiFile psiFile; + protected XmlFile xmlFile; @Override public void actionPerformed(AnActionEvent e) { @@ -93,7 +98,7 @@ protected void showAlert(int errorIndex) { dialog.setVisible(true); } - protected void createDirectoriesAndFilesIfNeeded(PsiDirectory psiParent, Mode mode) { + protected void createDirectoriesAndFilesIfNeeded(PsiDirectory psiParent) { for (Dimen datum : data) { WriteCommandAction.runWriteCommandAction(project, () -> { PsiDirectory subDirectory = psiParent.findSubdirectory(datum.getDirectory()); @@ -103,27 +108,21 @@ protected void createDirectoriesAndFilesIfNeeded(PsiDirectory psiParent, Mode mo PsiFile file = subDirectory.findFile(Constants.FILE_NAME); if (file == null) { PsiFile psiFile = subDirectory.createFile(Constants.FILE_NAME); - - Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile); document.setText(Constants.RESOURCES_TEXT); - fileCreationCompleteAndCheck(psiParent, mode); + fileCreationCompleteAndCheck(); } else { - fileCreationCompleteAndCheck(psiParent, mode); + fileCreationCompleteAndCheck(); } }); } } - protected void fileCreationCompleteAndCheck(PsiDirectory psiDirectory, Mode mode) { + protected void fileCreationCompleteAndCheck() { int value = fileCreationCount.incrementAndGet(); if (value == data.size()) { - if (mode == Mode.SINGLE) { - writeScaledValuesToFiles(psiDirectory, currentBucketIndex, values); - } else if (mode == Mode.BULK) { - writeBulkValuesToFiles(); - } + calculateAndWriteScaledValueToFiles(); } } @@ -139,32 +138,135 @@ private boolean isDimenFile(VirtualFile file) { return file != null && file.getName().endsWith(".xml") && file.getParent().getName().startsWith("values"); } - protected abstract void writeBulkValuesToFiles(); + protected abstract void calculateAndWriteScaledValueToFiles(); + + protected XmlTag[] getDimenValuesInFile(XmlFile xmlFile) { + XmlTag[] dimens = null; + if (xmlFile.getDocument() != null && xmlFile.getDocument().getRootTag() != null) { + String name = xmlFile.getDocument().getRootTag().getName(); + + switch (name) { + case "xml": + XmlTag resourcesTag = xmlFile.getDocument().getRootTag().findFirstSubTag("resources"); + if (resourcesTag != null) { + dimens = resourcesTag.findSubTags("dimen"); + } + break; + case "resources": + dimens = xmlFile.getDocument().getRootTag().findSubTags("dimen"); + break; + + } + } + return dimens; + } + + protected HashMap[] normalizeToHashMap(XmlTag[] dimens, int bucketIndex) { + HashMap dpHashMap = new HashMap<>(); + HashMap spHashMap = new HashMap<>(); + for (XmlTag tag : dimens) { + String val = tag.getValue().getText().toString().toLowerCase(); + try { + if (val.endsWith(Constants.DP)) { + dpHashMap.put(tag.getAttribute("name").getValue(), + Float.parseFloat(val.substring(0, val.length() - 2)) / data.get(bucketIndex).getFactorDp()); + } else if (val.endsWith(Constants.SP)) { + spHashMap.put(tag.getAttribute("name").getValue(), + Float.parseFloat(val.substring(0, val.length() - 2)) / data.get(bucketIndex).getFactorSp()); + } + } catch (NumberFormatException | ArithmeticException e) { + e.printStackTrace(); + } + + } + return new HashMap[]{dpHashMap, spHashMap}; + } + + protected void writeScaledValuesToFiles(PsiDirectory directory, HashMap[] floatDimen) { - protected void writeScaledValuesToFiles(PsiDirectory directory, int currentBucketIndex, String[] values) { - for (int i = 0; i < values.length; i++) { + for (int i = 0; i < data.size(); i++) { if (i != currentBucketIndex && data.get(i).isSelected()) { PsiFile file = directory.findSubdirectory(data.get(i).getDirectory()).findFile(Constants.FILE_NAME); + if (file instanceof XmlFile) { + XmlFile xmlFile = (XmlFile) file; + XmlTag[] tags = getDimenValuesInFile(xmlFile); + final int bucketIndex = i; + WriteCommandAction.runWriteCommandAction(project, new Runnable() { + @Override + public void run() { + StringBuilder stringBuilder = new StringBuilder(); + Document document = PsiDocumentManager.getInstance(project).getDocument(file); + document.setReadOnly(false); + String text = document.getText(); + int indexStart = text.indexOf("", indexStart) + 1; + stringBuilder.append(text.substring(0, index)); + stringBuilder.append("\n"); + Set setDp = new HashSet(floatDimen[0].keySet()); + Set setSp = new HashSet(floatDimen[1].keySet()); + for (int j = 0; tags != null && j < tags.length; j++) { + XmlTag tag = tags[j]; + String name = tag.getAttribute("name").getValue(); + if (floatDimen[0].containsKey(name)) { + String dimenFormattedString = MessageFormat.format(Constants.PLACEHOLDER_DIMEN, name + , getFormattedValue(floatDimen[0].get(name) * data.get(bucketIndex).getFactorDp()) + , Constants.DP); + stringBuilder.append(dimenFormattedString); + setDp.remove(name); + } else if (floatDimen[1].containsKey(name)) { + String dimenFormattedString = MessageFormat.format(Constants.PLACEHOLDER_DIMEN, name + , getFormattedValue(floatDimen[1].get(name) * data.get(bucketIndex).getFactorSp()) + , Constants.SP); + stringBuilder.append(dimenFormattedString); + setSp.remove(name); + } else { + String dimenFormattedString = MessageFormat.format(Constants.PLACEHOLDER_DIMEN, name + , tag.getValue().getText().toString() + , ""); + stringBuilder.append(dimenFormattedString); + } + } + for (String name : setDp) { + String dimenFormattedString = MessageFormat.format(Constants.PLACEHOLDER_DIMEN, name + , getFormattedValue(floatDimen[0].get(name) * data.get(bucketIndex).getFactorDp()) + , Constants.DP); + stringBuilder.append(dimenFormattedString); + } + for (String name : setSp) { + String dimenFormattedString = MessageFormat.format(Constants.PLACEHOLDER_DIMEN, name + , getFormattedValue(floatDimen[1].get(name) * data.get(bucketIndex).getFactorSp()) + , Constants.SP); + stringBuilder.append(dimenFormattedString); + } - final int x = i; - WriteCommandAction.runWriteCommandAction(project, new Runnable() { - @Override - public void run() { - Document document = PsiDocumentManager.getInstance(project).getDocument(file); - document.setReadOnly(false); - String text = document.getText(); - int indexStart = text.indexOf("", indexStart) + 1; - StringBuilder stringBuilder = new StringBuilder(text); - document.setText(stringBuilder.insert(index, "\n" + values[x]).toString()); + int suffixIndex = text.indexOf(""); + if (suffixIndex != -1) { + stringBuilder.append(text.substring(suffixIndex)); + } + document.setText(stringBuilder.toString()); + } } - } - }); - - + }); + } } } + + + } + + protected String getFormattedValue(float v) { + + DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.getDefault()); + otherSymbols.setDecimalSeparator('.'); + otherSymbols.setGroupingSeparator(','); + DecimalFormat formatter = new DecimalFormat("#.#", otherSymbols); + formatter.setGroupingUsed(false); + String s = formatter.format(v); + float floatedValue = Float.parseFloat(s); + int intValue = (int) floatedValue; + return intValue == floatedValue ? String.valueOf(intValue) : s; + } } diff --git a/src/com/hr/dimenify/action/BulkGenerateAction.java b/src/com/hr/dimenify/action/BulkGenerateAction.java index 3818034..7962e3b 100644 --- a/src/com/hr/dimenify/action/BulkGenerateAction.java +++ b/src/com/hr/dimenify/action/BulkGenerateAction.java @@ -5,19 +5,12 @@ import com.hr.dimenify.util.Constants; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.LangDataKeys; -import com.intellij.openapi.command.WriteCommandAction; -import com.intellij.openapi.editor.Document; -import com.intellij.psi.PsiDirectory; -import com.intellij.psi.PsiDocumentManager; -import com.intellij.psi.PsiFile; +import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.psi.xml.XmlFile; import com.intellij.psi.xml.XmlTag; -import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashMap; -import java.util.HashSet; -import java.util.Set; import static com.hr.dimenify.util.Constants.*; @@ -25,17 +18,12 @@ public class BulkGenerateAction extends AbstractDimenAction { private static final String TAG = "BulkGenerateAction"; - int currentBucketIndex; - - PsiFile psiFile; - XmlFile xmlFile; - @Override public void actionPerformed(AnActionEvent e) { super.actionPerformed(e); psiFile = e.getData(LangDataKeys.PSI_FILE); - if (psiFile instanceof XmlFile) { + if (psiFile.getFileType() == StdFileTypes.XML) { xmlFile = (XmlFile) psiFile; String folderName = psiFile.getParent().getName(); String bucket = null; @@ -67,7 +55,7 @@ private String[] showScaleDialog(String bucket, boolean isAdded) { int index = indexOfBucket(data, bucket); if (index != -1) { currentBucketIndex = index; - createDirectoriesAndFilesIfNeeded(psiFile.getParent().getParent(), Constants.Mode.BULK); + createDirectoriesAndFilesIfNeeded(psiFile.getParent().getParent()); } else { bulkDimenDialog.showAlert(MESSAGES.length); } @@ -87,7 +75,7 @@ private int indexOfBucket(ArrayList data, String bucket) { } @Override - protected void writeBulkValuesToFiles() { + protected void calculateAndWriteScaledValueToFiles() { XmlTag[] dimens = getDimenValuesInFile(xmlFile); if (dimens != null && dimens.length > 0) { HashMap[] floatDimen = normalizeToHashMap(dimens, currentBucketIndex); @@ -96,120 +84,6 @@ protected void writeBulkValuesToFiles() { } - private HashMap[] normalizeToHashMap(XmlTag[] dimens, int bucketIndex) { - HashMap dpHashMap = new HashMap<>(); - HashMap spHashMap = new HashMap<>(); - for (XmlTag tag : dimens) { - String val = tag.getValue().getText().toString().toLowerCase(); - try { - if (val.endsWith(Constants.DP)) { - dpHashMap.put(tag.getAttribute("name").getValue(), - Float.parseFloat(val.substring(0, val.length() - 2)) / data.get(bucketIndex).getFactorDp()); - } else if (val.endsWith(Constants.SP)) { - spHashMap.put(tag.getAttribute("name").getValue(), - Float.parseFloat(val.substring(0, val.length() - 2)) / data.get(bucketIndex).getFactorSp()); - } - } catch (NumberFormatException | ArithmeticException e) { - e.printStackTrace(); - } - - } - return new HashMap[]{dpHashMap, spHashMap}; - } - - private XmlTag[] getDimenValuesInFile(XmlFile xmlFile) { - XmlTag[] dimens = null; - if (xmlFile.getDocument() != null && xmlFile.getDocument().getRootTag() != null) { - String name = xmlFile.getDocument().getRootTag().getName(); - - switch (name) { - case "xml": - XmlTag resourcesTag = xmlFile.getDocument().getRootTag().findFirstSubTag("resources"); - if (resourcesTag != null) { - dimens = resourcesTag.findSubTags("dimen"); - } - break; - case "resources": - dimens = xmlFile.getDocument().getRootTag().findSubTags("dimen"); - break; - - } - } - return dimens; - } - - protected void writeScaledValuesToFiles(PsiDirectory directory, HashMap[] floatDimen) { - for (int i = 0; i < data.size(); i++) { - if (i != currentBucketIndex && data.get(i).isSelected()) { - PsiFile file = directory.findSubdirectory(data.get(i).getDirectory()).findFile(Constants.FILE_NAME); - if (file instanceof XmlFile) { - XmlFile xmlFile = (XmlFile) file; - XmlTag[] tags = getDimenValuesInFile(xmlFile); - final int bucketIndex = i; - WriteCommandAction.runWriteCommandAction(project, new Runnable() { - @Override - public void run() { - StringBuilder stringBuilder = new StringBuilder(); - Document document = PsiDocumentManager.getInstance(project).getDocument(file); - document.setReadOnly(false); - String text = document.getText(); - int indexStart = text.indexOf("", indexStart) + 1; - stringBuilder.append(text.substring(0, index)); - stringBuilder.append("\n"); - Set setDp = new HashSet(floatDimen[0].keySet()); - Set setSp = new HashSet(floatDimen[1].keySet()); - for (int j = 0; tags != null && j < tags.length; j++) { - XmlTag tag = tags[j]; - String name = tag.getAttribute("name").getValue(); - if (floatDimen[0].containsKey(name)) { - String dimenFormattedString = MessageFormat.format(Constants.PLACEHOLDER_DIMEN, name - , String.valueOf(floatDimen[0].get(name) * data.get(bucketIndex).getFactorDp()) - , Constants.DP); - stringBuilder.append(dimenFormattedString); - setDp.remove(name); - } else if (floatDimen[1].containsKey(name)) { - String dimenFormattedString = MessageFormat.format(Constants.PLACEHOLDER_DIMEN, name - , String.valueOf(floatDimen[1].get(name) * data.get(bucketIndex).getFactorSp()) - , Constants.SP); - stringBuilder.append(dimenFormattedString); - setSp.remove(name); - } else { - String dimenFormattedString = MessageFormat.format(Constants.PLACEHOLDER_DIMEN, name - , tag.getValue().getText().toString() - , ""); - stringBuilder.append(dimenFormattedString); - } - } - - for (String name : setDp) { - String dimenFormattedString = MessageFormat.format(Constants.PLACEHOLDER_DIMEN, name - , String.valueOf(floatDimen[0].get(name) * data.get(bucketIndex).getFactorDp()) - , Constants.DP); - stringBuilder.append(dimenFormattedString); - } - for (String name : setSp) { - String dimenFormattedString = MessageFormat.format(Constants.PLACEHOLDER_DIMEN, name - , String.valueOf(floatDimen[1].get(name) * data.get(bucketIndex).getFactorSp()) - , Constants.SP); - stringBuilder.append(dimenFormattedString); - } - - int suffixIndex = text.indexOf(""); - if (suffixIndex != -1) { - stringBuilder.append(text.substring(suffixIndex)); - } - document.setText(stringBuilder.toString()); - } - } - }); - } - } - } - - - } } diff --git a/src/com/hr/dimenify/action/GenerateSingleDimenAction.java b/src/com/hr/dimenify/action/GenerateSingleDimenAction.java index 63ac306..b6fe9e4 100644 --- a/src/com/hr/dimenify/action/GenerateSingleDimenAction.java +++ b/src/com/hr/dimenify/action/GenerateSingleDimenAction.java @@ -8,30 +8,30 @@ import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.fileTypes.StdFileTypes; -import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiFile; import com.intellij.psi.impl.source.xml.XmlAttributeImpl; import com.intellij.psi.impl.source.xml.XmlDocumentImpl; import com.intellij.psi.impl.source.xml.XmlTagImpl; import com.intellij.psi.impl.source.xml.XmlTextImpl; +import com.intellij.psi.xml.XmlFile; +import com.intellij.psi.xml.XmlTag; import javax.swing.*; -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -import java.text.MessageFormat; import java.util.ArrayList; -import java.util.Locale; +import java.util.HashMap; import static com.hr.dimenify.util.Constants.ERROR_CODE; public class GenerateSingleDimenAction extends AbstractDimenAction { + String attributeName; + + @Override public void actionPerformed(AnActionEvent e) { super.actionPerformed(e); - PsiFile psiFile = e.getData(LangDataKeys.PSI_FILE); + psiFile = e.getData(LangDataKeys.PSI_FILE); Editor editor = PlatformDataKeys.EDITOR.getData(e.getDataContext()); if (psiFile == null || editor == null) { @@ -42,6 +42,7 @@ public void actionPerformed(AnActionEvent e) { int offset = editor.getCaretModel().getOffset(); PsiElement psiElement = psiFile.findElementAt(offset); if (psiFile.getFileType() == StdFileTypes.XML) { + xmlFile = (XmlFile) psiFile; currentBucketIndex = getBucketIndex(psiFile); if (currentBucketIndex == -1) { if (data.size() == 10) { @@ -70,37 +71,40 @@ public void actionPerformed(AnActionEvent e) { } } - values = getInsertionValuesElement(psiElement); - if (values == null) { - e.getPresentation().setEnabled(false); - return; - } else { - if (psiFile.getParent().getParent() != null) { - PsiDirectory psiDirectory = psiFile.getParent().getParent(); - createDirectoriesAndFilesIfNeeded(psiDirectory, Constants.Mode.SINGLE); - - } - } + initialize(psiElement); } else { e.getPresentation().setEnabled(false); return; } } - @Override - protected void writeBulkValuesToFiles() { + protected void calculateAndWriteScaledValueToFiles() { + XmlTag[] dimens = getDimenValuesInFile(xmlFile); + for (XmlTag tag : dimens) { + try { + if (tag.getAttribute("name").getValue().equalsIgnoreCase(attributeName)) { + dimens = new XmlTag[]{tag}; + break; + } + } catch (Exception e) { + return; + } + } + if (dimens != null && dimens.length > 0) { + HashMap[] floatDimen = normalizeToHashMap(dimens, currentBucketIndex); + writeScaledValuesToFiles(psiFile.getParent().getParent(), floatDimen); + } } - private String[] getInsertionValuesElement(PsiElement psiElement) { + private void initialize(PsiElement psiElement) { PsiElement selectedNode = psiElement; PsiElement rootParent; PsiElement subNode; if (psiElement != null && psiElement.getParent() != null && psiElement.getParent().getParent() != null) { subNode = psiElement.getParent(); rootParent = subNode.getParent(); - ArrayList elementHierachy = new ArrayList<>(); while (!(rootParent instanceof XmlDocumentImpl) && (!(selectedNode instanceof XmlTagImpl) || !((XmlTagImpl) selectedNode).getName().equals(Constants.DIMEN_TAG))) { rootParent = rootParent.getParent(); @@ -122,61 +126,32 @@ private String[] getInsertionValuesElement(PsiElement psiElement) { } if (attribute != null) { - String attributeName = attribute.getValue(); + attributeName = attribute.getValue(); String val = value.getValue().toLowerCase().trim(); - if (val.endsWith(Constants.DP) || val.endsWith(Constants.SP)) { - - return showScaleDialog(attributeName, val, val.endsWith(Constants.DP)); + showScaleDialog(val.endsWith(Constants.DP)); } } } } - return null; - } else { - return null; } } - private String[] showScaleDialog(String attributeName, String val, boolean isDp) { + private void showScaleDialog(boolean isDp) { SingleDimenDialog singleDimenDialog = new SingleDimenDialog(project, isDp, data); singleDimenDialog.show(); int invalidIndex = singleDimenDialog.invalidBucketIndex(); if (singleDimenDialog.isOK() && (invalidIndex == -1 || (invalidIndex == ERROR_CODE[1] && data.size() == Constants.MAX_DIMENS))) { - DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.getDefault()); - otherSymbols.setDecimalSeparator('.'); - otherSymbols.setGroupingSeparator(','); - DecimalFormat formatter = new DecimalFormat("#0.0", otherSymbols); + ArrayList data = singleDimenDialog.getConversionValues(); saveValues(data); + createDirectoriesAndFilesIfNeeded(psiFile.getParent().getParent()); - - float scaleFactor[] = new float[data.size()]; - for (int i = 0; i < data.size(); i++) { - scaleFactor[i] = isDp ? data.get(i).getFactorDp() : data.get(i).getFactorSp(); - } - float mdpiValue = 0; - try { - mdpiValue = Float.parseFloat(val.substring(0, val.length() - 2)) / scaleFactor[currentBucketIndex]; - } catch (NullPointerException | NumberFormatException e) { - return null; - } - float scaledValues[] = new float[scaleFactor.length]; - String elementsScaled[] = new String[scaleFactor.length]; - - for (int i = 0; i < scaledValues.length; i++) { - scaledValues[i] = mdpiValue * scaleFactor[i]; - elementsScaled[i] = MessageFormat.format(Constants.PLACEHOLDER_DIMEN, attributeName - , formatter.format(scaledValues[i]) - , val.endsWith(Constants.DP) ? Constants.DP : Constants.SP); - } - return elementsScaled; } else if (singleDimenDialog.isOK()) { singleDimenDialog.showAlert(invalidIndex); } - return null; } diff --git a/src/com/hr/dimenify/util/Constants.java b/src/com/hr/dimenify/util/Constants.java index 26de6b8..11d2a32 100644 --- a/src/com/hr/dimenify/util/Constants.java +++ b/src/com/hr/dimenify/util/Constants.java @@ -12,7 +12,7 @@ public interface Constants { String MDPI = "mdpi"; float TITLE_SIZE = 16.0f; String NAME_TAG = "name"; - String PLACEHOLDER_DIMEN = "{1}{2}\n"; + String PLACEHOLDER_DIMEN = "\t{1}{2}\n"; String FILE_NAME = "dimens.xml"; String VALUES_PREFIX = "values-"; String DP = "dp";