OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Compare Revisions

Ignore whitespace Rev 180 → Rev 181

/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/component/ComponentCreateMainPanel.java
9,12 → 9,12
 
public ComponentCreateMainPanel(Extension extension) {
super(extension);
split.setDividerLocation(0.5D);
this.split.setDividerLocation(0.5D);
}
 
@Override
public JComponent createLeftComponent() {
return new ComponentListPanel(extension, this);
return new ComponentListPanel(this.extension, this);
}
 
public void select(ComponentDescritor listDescriptor) {
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/component/GroupDescritor.java
23,7 → 23,7
}
 
public String getId() {
return id;
return this.id;
}
 
public void setId(String id) {
31,7 → 31,7
}
 
public Group getGroup() {
return group;
return this.group;
}
 
@Override
40,7 → 40,7
}
 
public boolean containsGroupId(String gId) {
return containsGroup(group, gId);
return containsGroup(this.group, gId);
}
 
private boolean containsGroup(Item item, String gId) {
61,7 → 61,7
}
 
public Item getItemFromId(String id) {
return getItemFromId(group, id);
return getItemFromId(this.group, id);
}
 
private Item getItemFromId(Item item, String gId) {
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/component/GroupTreeModel.java
19,7 → 19,7
}
 
public void setShowAll(boolean b) {
if (b != showAll) {
if (b != this.showAll) {
this.showAll = b;
System.err.println("GroupTreeModel.setShowAll()" + b);
reload();
68,7 → 68,7
final ActivableMutableTreeNode newChild = new ActivableMutableTreeNode(item);
 
newChild.setActive(n.containsGroupId(item.getId()));
if (showAll || newChild.isActive()) {
if (this.showAll || newChild.isActive()) {
node.add(newChild);
}
if (item instanceof Group) {
102,7 → 102,7
this.componentDescriptor.removeGroup(item);
}
reload(n);
componentDescriptor.fireGroupChanged();
this.componentDescriptor.fireGroupChanged();
}
 
@Override
109,7 → 109,7
protected void fireTreeNodesInserted(Object source, Object[] path, int[] childIndices, Object[] children) {
// To update preview while reordering
super.fireTreeNodesInserted(source, path, childIndices, children);
componentDescriptor.fireGroupChanged();
this.componentDescriptor.fireGroupChanged();
}
 
@Override
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/component/ComponentListPanel.java
22,7 → 22,7
 
@Override
public void addNewItem() {
((CreateComponentListModel) dataModel).addComponentList();
((CreateComponentListModel) this.dataModel).addComponentList();
}
 
@Override
39,8 → 39,8
 
@Override
public void removeItem(Object item) {
((CreateComponentListModel) dataModel).removeElement(item);
extension.removeCreateComponent((ComponentDescritor) item);
((CreateComponentListModel) this.dataModel).removeElement(item);
this.extension.removeCreateComponent((ComponentDescritor) item);
}
 
@Override
47,10 → 47,10
public void itemSelected(Object item) {
if (item != null) {
ComponentDescritor n = (ComponentDescritor) item;
final ComponentCreatePanel p = new ComponentCreatePanel(n, extension);
tableInfoPanel.setRightPanel(p);
final ComponentCreatePanel p = new ComponentCreatePanel(n, this.extension);
this.tableInfoPanel.setRightPanel(p);
} else {
tableInfoPanel.setRightPanel(new JPanel());
this.tableInfoPanel.setRightPanel(new JPanel());
}
}
}
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/component/ComponentDescritor.java
16,7 → 16,7
}
 
public String getTable() {
return table;
return this.table;
}
 
 
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/component/CreateComponentListModel.java
22,13 → 22,13
@Override
public void stateChanged(ChangeEvent e) {
this.clear();
addContent(extension);
addContent(this.extension);
}
 
public void addComponentList() {
final ComponentDescritor l = new ComponentDescritor("Interface de saisie " + (this.getSize() + 1));
this.addElement(l);
extension.addCreateComponent(l);
this.extension.addCreateComponent(l);
}
 
}
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/component/GroupEditor.java
61,8 → 61,8
c.insets = new Insets(2, 2, 2, 0);
 
panel.add(new JLabelBold("Champs et groupes"), c);
newModel = new ItemTreeModel();
tree = new ReorderableJTree() {
this.newModel = new ItemTreeModel();
this.tree = new ReorderableJTree() {
@Override
public String convertValueToText(Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
final Object userObject = ((DefaultMutableTreeNode) value).getUserObject();
76,10 → 76,10
return userObject.toString();
}
};
tree.setModel(newModel);
tree.setRootVisible(false);
tree.setShowsRootHandles(true);
tree.expandRow(0);
this.tree.setModel(this.newModel);
this.tree.setRootVisible(false);
this.tree.setShowsRootHandles(true);
this.tree.expandRow(0);
final DefaultTreeCellRenderer treeRenderer = new DefaultTreeCellRenderer() {
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
97,8 → 97,8
};
 
treeRenderer.setLeafIcon(null);
tree.setCellRenderer(treeRenderer);
final JScrollPane comp2 = new JScrollPane(tree);
this.tree.setCellRenderer(treeRenderer);
final JScrollPane comp2 = new JScrollPane(this.tree);
comp2.setMinimumSize(new Dimension(250, 150));
comp2.setPreferredSize(new Dimension(250, 150));
c.weighty = 1;
139,7 → 139,7
showHideButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
newModel.toggleActive(tree.getSelectionPath());
GroupEditor.this.newModel.toggleActive(GroupEditor.this.tree.getSelectionPath());
}
});
 
147,36 → 147,36
 
@Override
public void actionPerformed(ActionEvent e) {
newModel.setShowAll(hideCheckbox.isSelected());
setMainTable(n.getTable());
GroupEditor.this.newModel.setShowAll(hideCheckbox.isSelected());
setMainTable(GroupEditor.this.n.getTable());
setRightPanel(new JPanel());
}
});
 
tree.addTreeSelectionListener(new TreeSelectionListener() {
this.tree.addTreeSelectionListener(new TreeSelectionListener() {
 
@Override
public void valueChanged(TreeSelectionEvent e) {
final Object selectedValue = tree.getSelectionPath();
final Object selectedValue = GroupEditor.this.tree.getSelectionPath();
showHideButton.setEnabled((selectedValue != null));
}
});
tree.addMouseListener(new MouseAdapter() {
this.tree.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() > 1) {
newModel.toggleActive(tree.getSelectionPath());
GroupEditor.this.newModel.toggleActive(GroupEditor.this.tree.getSelectionPath());
}
}
 
@Override
public void mousePressed(MouseEvent e) {
final TreePath selectionPath = tree.getSelectionPath();
final TreePath selectionPath = GroupEditor.this.tree.getSelectionPath();
if (selectionPath == null) {
setRightPanel(new JPanel());
} else {
Item i = (Item) ((DefaultMutableTreeNode) selectionPath.getLastPathComponent()).getUserObject();
setRightPanel(new ItemEditor(i, n));
setRightPanel(new ItemEditor(i, GroupEditor.this.n));
}
}
});
184,31 → 184,31
}
 
protected void addNewGroup() {
final DefaultMutableTreeNode root = (DefaultMutableTreeNode) ((DefaultMutableTreeNode) (tree.getModel().getRoot())).getFirstChild();
final DefaultMutableTreeNode root = (DefaultMutableTreeNode) ((DefaultMutableTreeNode) (this.tree.getModel().getRoot())).getFirstChild();
DefaultMutableTreeNode node = root;
if (node.getChildCount() > 0) {
node = (DefaultMutableTreeNode) node.getFirstChild();
}
if (tree.getSelectionPath() != null) {
node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
if (this.tree.getSelectionPath() != null) {
node = (DefaultMutableTreeNode) this.tree.getLastSelectedPathComponent();
}
if (node != root) {
DefaultMutableTreeNode newNode = new ActivableMutableTreeNode(new Group("group" + node.getParent().getChildCount() + 1));
final DefaultMutableTreeNode parent = (DefaultMutableTreeNode) node.getParent();
parent.insert(newNode, parent.getIndex(node));
newModel.reload();
tree.setSelectionPath(new TreePath(newModel.getPathToRoot(newNode)));
this.newModel.reload();
this.tree.setSelectionPath(new TreePath(this.newModel.getPathToRoot(newNode)));
}
 
}
 
public void setMainTable(String table) {
n.setTable(table);
this.n.setTable(table);
 
initGroupFromTable(extension.getAllKnownFieldName(table));
newModel.fillFromGroup(n, this.tableGroup);
initGroupFromTable(this.extension.getAllKnownFieldName(table));
this.newModel.fillFromGroup(this.n, this.tableGroup);
 
tree.expandRow(0);
this.tree.expandRow(0);
}
 
public void initGroupFromTable(List<String> fields) {
215,9 → 215,9
System.out.println("GroupEditor.initGroupFromTable()");
System.out.println("GroupEditor.initGroupFromTable Component group");
 
this.tableGroup = new Group(n.getId());
this.tableGroup = new Group(this.n.getId());
for (String field : fields) {
Item i = n.getItemFromId(field);
Item i = this.n.getItemFromId(field);
Item newItem = new Item(field);
 
if (i != null) {
232,11 → 232,11
 
public Group getFilteredGroup() {
// Parcours du Tree
Group filteredGroup = new Group(n.getId());
if (n.getTable() == null) {
throw new IllegalStateException("Not table defined for " + n);
Group filteredGroup = new Group(this.n.getId());
if (this.n.getTable() == null) {
throw new IllegalStateException("Not table defined for " + this.n);
}
walk(newModel, filteredGroup, newModel.getRoot());
walk(this.newModel, filteredGroup, this.newModel.getRoot());
filteredGroup = (Group) filteredGroup.getItem(0);
 
return filteredGroup;
256,7 → 256,7
} else {
final Item item = new Item(userObject.getId());
item.setLocalHint(new LayoutHints(userObject.getLocalHint()));
final SQLTable table = ComptaPropsConfiguration.getInstanceCompta().getRootSociete().getTable(n.getTable());
final SQLTable table = ComptaPropsConfiguration.getInstanceCompta().getRootSociete().getTable(this.n.getTable());
if (table.contains(userObject.getId())) {
SQLField field = table.getField(userObject.getId());
if (!field.isPrimaryKey() && !field.getName().endsWith("ORDRE") && !field.getName().endsWith("ARCHIVE")) {
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/component/ItemEditor.java
47,8 → 47,8
c.gridx++;
c.weightx = 1;
c.fill = GridBagConstraints.HORIZONTAL;
textId = new JTextField(30);
this.add(textId, c);
this.textId = new JTextField(30);
this.add(this.textId, c);
c.gridy++;
} else {
// Label du champs
77,8 → 77,8
c.gridx++;
c.fill = GridBagConstraints.NONE;
c.weightx = 1;
comboType = new JComboBox(new String[] { "normal", "large", "très large" });
this.add(comboType, c);
this.comboType = new JComboBox(new String[] { "normal", "large", "très large" });
this.add(this.comboType, c);
c.gridy++;
}
c.gridx = 0;
92,9 → 92,9
this.add(labelSep, c);
c.gridx++;
c.fill = GridBagConstraints.NONE;
checkSeparated = new JCheckBox();
this.checkSeparated = new JCheckBox();
c.weightx = 1;
this.add(checkSeparated, c);
this.add(this.checkSeparated, c);
c.gridx = 0;
c.gridy++;
if (!this.isEditingGroup) {
104,9 → 104,9
c.gridx++;
c.weightx = 1;
c.fill = GridBagConstraints.NONE;
checkLabel = new JCheckBox();
this.checkLabel = new JCheckBox();
 
this.add(checkLabel, c);
this.add(this.checkLabel, c);
 
c.gridy++;
 
117,8 → 117,8
c.gridx++;
c.fill = GridBagConstraints.NONE;
c.weightx = 1;
checkFillH = new JCheckBox();
this.add(checkFillH, c);
this.checkFillH = new JCheckBox();
this.add(this.checkFillH, c);
c.gridy++;
}
 
129,8 → 129,8
initUIFrom(item);
 
// Listeners
if (isEditingGroup) {
textId.getDocument().addDocumentListener(new DocumentListener() {
if (this.isEditingGroup) {
this.textId.getDocument().addDocumentListener(new DocumentListener() {
 
@Override
public void removeUpdate(DocumentEvent e) {
146,44 → 146,44
 
@Override
public void changedUpdate(DocumentEvent e) {
item.setId(textId.getText());
item.setId(ItemEditor.this.textId.getText());
component.fireGroupChanged();
 
}
});
}
checkSeparated.addActionListener(new ActionListener() {
this.checkSeparated.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
item.setLocalHint(item.getLocalHint().getBuilder().setSeparated(checkSeparated.isSelected()).build());
item.setLocalHint(item.getLocalHint().getBuilder().setSeparated(ItemEditor.this.checkSeparated.isSelected()).build());
component.fireGroupChanged();
}
});
 
if (!isEditingGroup) {
checkLabel.addActionListener(new ActionListener() {
if (!this.isEditingGroup) {
this.checkLabel.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
item.setLocalHint(item.getLocalHint().getBuilder().setShowLabel(checkLabel.isSelected()).build());
item.setLocalHint(item.getLocalHint().getBuilder().setShowLabel(ItemEditor.this.checkLabel.isSelected()).build());
component.fireGroupChanged();
}
});
checkFillH.addActionListener(new ActionListener() {
this.checkFillH.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
item.setLocalHint(item.getLocalHint().getBuilder().setFillHeight(checkFillH.isSelected()).build());
item.setLocalHint(item.getLocalHint().getBuilder().setFillHeight(ItemEditor.this.checkFillH.isSelected()).build());
component.fireGroupChanged();
}
});
 
comboType.addActionListener(new ActionListener() {
this.comboType.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
int i = comboType.getSelectedIndex();
int i = ItemEditor.this.comboType.getSelectedIndex();
final LayoutHintsBuilder h = item.getLocalHint().getBuilder();
if (i == 0) {
h.setFillWidth(false);
208,20 → 208,20
 
final LayoutHints localHint = item.getLocalHint();
 
checkSeparated.setSelected(localHint.isSeparated());
this.checkSeparated.setSelected(localHint.isSeparated());
 
if (!isEditingGroup) {
if (!this.isEditingGroup) {
if (localHint.fillWidth() && localHint.largeWidth()) {
comboType.setSelectedIndex(2);
this.comboType.setSelectedIndex(2);
} else if (localHint.fillWidth()) {
comboType.setSelectedIndex(1);
this.comboType.setSelectedIndex(1);
} else {
comboType.setSelectedIndex(0);
this.comboType.setSelectedIndex(0);
}
checkFillH.setSelected(localHint.fillHeight());
checkLabel.setSelected(localHint.showLabel());
this.checkFillH.setSelected(localHint.fillHeight());
this.checkLabel.setSelected(localHint.showLabel());
} else {
textId.setText(item.getId());
this.textId.setText(item.getId());
 
}
}
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/component/ComponentCreatePanel.java
58,16 → 58,16
c.gridwidth = 2;
c.fill = GridBagConstraints.BOTH;
 
panel = new GroupEditor(n, extension);
this.panel = new GroupEditor(n, extension);
final String mainTable = n.getTable();
if (mainTable == null && comboTable.getModel().getSize() > 0) {
comboTable.setSelectedIndex(0);
panel.setMainTable((String) comboTable.getModel().getElementAt(0));
this.panel.setMainTable((String) comboTable.getModel().getElementAt(0));
} else {
comboTable.setSelectedItem(mainTable);
panel.setMainTable(mainTable);
this.panel.setMainTable(mainTable);
}
this.add(panel, c);
this.add(this.panel, c);
 
final JButton previewButton = new JButton("Prévisualiser");
c.gridy++;
82,7 → 82,7
 
@Override
public void actionPerformed(ActionEvent e) {
panel.setMainTable((String) comboTable.getSelectedItem());
ComponentCreatePanel.this.panel.setMainTable((String) comboTable.getSelectedItem());
 
}
});
96,7 → 96,7
JOptionPane.showMessageDialog(ComponentCreatePanel.this, "La table doit être créée avant de pouvoir prévisualiser.");
return;
}
final Group group = panel.getFilteredGroup();
final Group group = ComponentCreatePanel.this.panel.getFilteredGroup();
 
final SQLElement element = ComptaPropsConfiguration.getInstanceCompta().getDirectory().getElement(t);
if (element == null) {
103,17 → 103,17
Log.get().warning("No element for table: " + t.getName());
}
final GroupSQLComponent gComponent = new ExtensionGroupSQLComponent(element, group);
oldGroup = group;
if (previewFrame == null || !previewFrame.isVisible()) {
previewFrame = new JFrame();
previewFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
previewFrame.setTitle("Preview: " + group.getId());
ComponentCreatePanel.this.oldGroup = group;
if (ComponentCreatePanel.this.previewFrame == null || !ComponentCreatePanel.this.previewFrame.isVisible()) {
ComponentCreatePanel.this.previewFrame = new JFrame();
ComponentCreatePanel.this.previewFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
ComponentCreatePanel.this.previewFrame.setTitle("Preview: " + group.getId());
}
final EditPanel panel = new EditPanel(gComponent, EditMode.CREATION);
previewFrame.setContentPane(panel);
previewFrame.pack();
if (!previewFrame.isVisible()) {
FrameUtil.show(previewFrame);
ComponentCreatePanel.this.previewFrame.setContentPane(panel);
ComponentCreatePanel.this.previewFrame.pack();
if (!ComponentCreatePanel.this.previewFrame.isVisible()) {
FrameUtil.show(ComponentCreatePanel.this.previewFrame);
}
 
};
123,15 → 123,15
 
@Override
public void stateChanged(ChangeEvent e) {
if (previewFrame == null || !previewFrame.isVisible()) {
if (ComponentCreatePanel.this.previewFrame == null || !ComponentCreatePanel.this.previewFrame.isVisible()) {
return;
}
final Group group = panel.getFilteredGroup();
if (group.equalsDesc(oldGroup)) {
final Group group = ComponentCreatePanel.this.panel.getFilteredGroup();
if (group.equalsDesc(ComponentCreatePanel.this.oldGroup)) {
// Avoid refresh when group doesn't change
return;
}
oldGroup = group;
ComponentCreatePanel.this.oldGroup = group;
final SQLTable t = ComptaPropsConfiguration.getInstanceCompta().getRootSociete().getTable(n.getTable());
if (t == null) {
return;
138,10 → 138,10
}
final SQLElement element = ComptaPropsConfiguration.getInstanceCompta().getDirectory().getElement(t);
final GroupSQLComponent gComponent = new ExtensionGroupSQLComponent(element, group);
previewFrame.setContentPane(new EditPanel(gComponent, EditMode.CREATION));
previewFrame.pack();
if (!previewFrame.isVisible()) {
FrameUtil.show(previewFrame);
ComponentCreatePanel.this.previewFrame.setContentPane(new EditPanel(gComponent, EditMode.CREATION));
ComponentCreatePanel.this.previewFrame.pack();
if (!ComponentCreatePanel.this.previewFrame.isVisible()) {
FrameUtil.show(ComponentCreatePanel.this.previewFrame);
}
 
}
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/component/ActivableMutableTreeNode.java
14,7 → 14,7
}
 
public boolean isActive() {
return active;
return this.active;
}
 
}
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/menu/MenuMainPanel.java
7,7 → 7,6
 
import org.openconcerto.modules.extensionbuilder.Extension;
import org.openconcerto.modules.extensionbuilder.menu.mainmenu.MainMenuPanel;
import org.openconcerto.modules.extensionbuilder.meu.actions.ActionMainPanel;
 
public class MenuMainPanel extends JPanel {
final MainMenuPanel mainMenuPanel;
15,9 → 14,10
public MenuMainPanel(Extension extension) {
this.setLayout(new GridLayout(1, 1));
JTabbedPane tab = new JTabbedPane();
mainMenuPanel = new MainMenuPanel(extension);
tab.addTab("Menu principal", mainMenuPanel);
tab.addTab("Actions contextuelles", new ActionMainPanel(extension));
this.mainMenuPanel = new MainMenuPanel(extension);
tab.addTab("Menu principal", this.mainMenuPanel);
// TODO : terminer la gestion des actions
// tab.addTab("Actions contextuelles", new ActionMainPanel(extension));
this.add(tab);
}
 
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/menu/mainmenu/MainMenuGroupEditor.java
49,20 → 49,20
}
 
public void fillModel() {
newModel.fillFromDescriptor(extension);
tree.setModel(newModel);
this.newModel.fillFromDescriptor(this.extension);
this.tree.setModel(this.newModel);
expand();
 
}
 
private void expand() {
tree.expandRow(0);
this.tree.expandRow(0);
 
final List<MenuDescriptor> m = new ArrayList<MenuDescriptor>();
m.addAll(extension.getCreateMenuList());
m.addAll(extension.getRemoveMenuList());
m.addAll(this.extension.getCreateMenuList());
m.addAll(this.extension.getRemoveMenuList());
for (MenuDescriptor menuDescriptor : m) {
final DefaultMutableTreeNode root = (DefaultMutableTreeNode) tree.getModel().getRoot();
final DefaultMutableTreeNode root = (DefaultMutableTreeNode) this.tree.getModel().getRoot();
@SuppressWarnings("unchecked")
final Enumeration<DefaultMutableTreeNode> e = root.depthFirstEnumeration();
while (e.hasMoreElements()) {
72,7 → 72,7
final String nodeLabel = ((Item) userObject).getId();
if (nodeLabel != null && nodeLabel.equals(menuDescriptor.getId())) {
final TreePath path = new TreePath(((DefaultMutableTreeNode) node.getParent()).getPath());
tree.expandPath(path);
this.tree.expandPath(path);
}
}
}
92,11 → 92,11
c.insets = new Insets(2, 2, 2, 0);
 
panel.add(new JLabel("Menus"), c);
newModel = new MenuItemTreeModel();
tree = new ReorderableJTree();
tree.setModel(newModel);
tree.setRootVisible(false);
tree.setShowsRootHandles(true);
this.newModel = new MenuItemTreeModel();
this.tree = new ReorderableJTree();
this.tree.setModel(this.newModel);
this.tree.setRootVisible(false);
this.tree.setShowsRootHandles(true);
 
final DefaultTreeCellRenderer treeRenderer = new DefaultTreeCellRenderer() {
@Override
109,7 → 109,7
final JLabel r = (JLabel) super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
if (tr.getUserObject() instanceof Item) {
final String id = ((Item) tr.getUserObject()).getId();
if (extension.getCreateMenuItemFromId(id) != null) {
if (MainMenuGroupEditor.this.extension.getCreateMenuItemFromId(id) != null) {
r.setForeground(new Color(50, 80, 150));
}
}
116,13 → 116,16
if (!tr.isActive()) {
r.setForeground(Color.LIGHT_GRAY);
}
if (sel) {
r.setForeground(Color.WHITE);
}
return r;
}
};
 
treeRenderer.setLeafIcon(null);
tree.setCellRenderer(treeRenderer);
final JScrollPane comp2 = new JScrollPane(tree);
this.tree.setCellRenderer(treeRenderer);
final JScrollPane comp2 = new JScrollPane(this.tree);
comp2.setMinimumSize(new Dimension(250, 150));
comp2.setPreferredSize(new Dimension(250, 150));
c.weighty = 1;
170,13 → 173,13
removeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final TreePath selectionPath = tree.getSelectionPath();
final TreePath selectionPath = MainMenuGroupEditor.this.tree.getSelectionPath();
if (selectionPath != null) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectionPath.getLastPathComponent();
if (node.getUserObject() != null) {
String idToDelete = ((Item) node.getUserObject()).getId();
extension.removeCreateMenuForId(idToDelete);
extension.setChanged();
MainMenuGroupEditor.this.extension.removeCreateMenuForId(idToDelete);
MainMenuGroupEditor.this.extension.setChanged();
fillModel();
}
 
187,21 → 190,21
 
@Override
public void actionPerformed(ActionEvent e) {
newModel.setShowAll(hideCheckbox.isSelected());
newModel.fillFromDescriptor(extension);
MainMenuGroupEditor.this.newModel.setShowAll(hideCheckbox.isSelected());
MainMenuGroupEditor.this.newModel.fillFromDescriptor(MainMenuGroupEditor.this.extension);
}
 
});
tree.addTreeSelectionListener(new TreeSelectionListener() {
this.tree.addTreeSelectionListener(new TreeSelectionListener() {
 
@Override
public void valueChanged(TreeSelectionEvent e) {
final TreePath selectionPath = tree.getSelectionPath();
final TreePath selectionPath = MainMenuGroupEditor.this.tree.getSelectionPath();
if (selectionPath != null) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectionPath.getLastPathComponent();
if (node.getUserObject() != null) {
String selectedId = ((Item) node.getUserObject()).getId();
removeButton.setEnabled(extension.getCreateMenuItemFromId(selectedId) != null);
removeButton.setEnabled(MainMenuGroupEditor.this.extension.getCreateMenuItemFromId(selectedId) != null);
}
} else {
removeButton.setEnabled(false);
209,26 → 212,26
 
}
});
tree.addMouseListener(new MouseAdapter() {
this.tree.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() > 1) {
newModel.toggleActive(tree.getSelectionPath());
MainMenuGroupEditor.this.newModel.toggleActive(MainMenuGroupEditor.this.tree.getSelectionPath());
}
}
 
@Override
public void mousePressed(MouseEvent e) {
final TreePath selectionPath = tree.getSelectionPath();
final TreePath selectionPath = MainMenuGroupEditor.this.tree.getSelectionPath();
if (selectionPath == null) {
setRightPanel(new JPanel());
} else {
Item i = (Item) ((DefaultMutableTreeNode) selectionPath.getLastPathComponent()).getUserObject();
setRightPanel(new MenuItemEditor(newModel, i, extension));
setRightPanel(new MenuItemEditor(MainMenuGroupEditor.this.newModel, i, MainMenuGroupEditor.this.extension));
}
}
});
tree.getModel().addTreeModelListener(new TreeModelListener() {
this.tree.getModel().addTreeModelListener(new TreeModelListener() {
 
@Override
public void treeStructureChanged(TreeModelEvent e) {
257,13 → 260,13
}
 
protected void addNewGroup() {
final DefaultMutableTreeNode root = (DefaultMutableTreeNode) ((DefaultMutableTreeNode) (tree.getModel().getRoot())).getFirstChild();
final DefaultMutableTreeNode root = (DefaultMutableTreeNode) ((DefaultMutableTreeNode) (this.tree.getModel().getRoot())).getFirstChild();
DefaultMutableTreeNode node = root;
if (node.getChildCount() > 0) {
node = (DefaultMutableTreeNode) node.getFirstChild();
}
if (tree.getSelectionPath() != null) {
node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
if (this.tree.getSelectionPath() != null) {
node = (DefaultMutableTreeNode) this.tree.getLastSelectedPathComponent();
}
if (node != root) {
final String newGroupId = "group" + node.getParent().getChildCount() + 1;
274,23 → 277,23
final MenuDescriptor desc = new MenuDescriptor(newGroupId);
desc.setType(MenuDescriptor.GROUP);
desc.setInsertInMenu(((Item) parent.getUserObject()).getId());
extension.addCreateMenu(desc);
extension.setChanged();
this.extension.addCreateMenu(desc);
this.extension.setChanged();
 
newModel.reload();
tree.setSelectionPath(new TreePath(newModel.getPathToRoot(newNode)));
this.newModel.reload();
this.tree.setSelectionPath(new TreePath(this.newModel.getPathToRoot(newNode)));
}
extension.setChanged();
this.extension.setChanged();
}
 
protected void addNewItem() {
final DefaultMutableTreeNode root = (DefaultMutableTreeNode) ((DefaultMutableTreeNode) (tree.getModel().getRoot())).getFirstChild();
final DefaultMutableTreeNode root = (DefaultMutableTreeNode) ((DefaultMutableTreeNode) (this.tree.getModel().getRoot())).getFirstChild();
DefaultMutableTreeNode node = root;
if (node.getChildCount() > 0) {
node = (DefaultMutableTreeNode) node.getFirstChild();
}
if (tree.getSelectionPath() != null) {
node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
if (this.tree.getSelectionPath() != null) {
node = (DefaultMutableTreeNode) this.tree.getLastSelectedPathComponent();
}
if (node != root) {
final String newActionId = "action" + node.getParent().getChildCount() + 1;
300,10 → 303,10
final MenuDescriptor desc = new MenuDescriptor(newActionId);
desc.setType(MenuDescriptor.CREATE);
desc.setInsertInMenu(((Item) parent.getUserObject()).getId());
extension.addCreateMenu(desc);
extension.setChanged();
newModel.reload();
tree.setSelectionPath(new TreePath(newModel.getPathToRoot(newNode)));
this.extension.addCreateMenu(desc);
this.extension.setChanged();
this.newModel.reload();
this.tree.setSelectionPath(new TreePath(this.newModel.getPathToRoot(newNode)));
}
 
}
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/menu/mainmenu/MenuDescriptor.java
16,7 → 16,7
}
 
public String getId() {
return id;
return this.id;
}
 
public void setId(String id) {
24,7 → 24,7
}
 
public String getListId() {
return listId;
return this.listId;
}
 
public void setListId(String listId) {
32,7 → 32,7
}
 
public String getComponentId() {
return componentId;
return this.componentId;
}
 
public void setComponentId(String componentId) {
44,7 → 44,7
* @return "list" or "create"
* */
public String getType() {
return type;
return this.type;
}
 
public void setType(String type) {
52,7 → 52,7
}
 
public String getInsertInMenu() {
return insertInMenu;
return this.insertInMenu;
}
 
public void setInsertInMenu(String insertInMenu) {
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/menu/mainmenu/MenuItemTreeModel.java
64,7 → 64,7
depth++;
final ActivableMutableTreeNode newChild = new ActivableMutableTreeNode(item);
newChild.setActive(isActive(item.getId()));
if (showAll || newChild.isActive()) {
if (this.showAll || newChild.isActive()) {
node.add(newChild);
}
if (item instanceof Group) {
81,7 → 81,7
}
 
private boolean isActive(String id) {
List<MenuDescriptor> l = extension.getRemoveMenuList();
List<MenuDescriptor> l = this.extension.getRemoveMenuList();
for (MenuDescriptor menuDescriptor : l) {
if (menuDescriptor.getId().equals(id)) {
return false;
108,11 → 108,11
 
public void setActive(boolean active, String id) {
if (active) {
extension.removeRemoveMenuForId(id);
this.extension.removeRemoveMenuForId(id);
} else {
extension.addRemoveMenu(new MenuDescriptor(id));
this.extension.addRemoveMenu(new MenuDescriptor(id));
}
extension.setChanged();
this.extension.setChanged();
 
DefaultMutableTreeNode n = getNode(id);
if (n != null) {
137,9 → 137,9
public void insertNodeInto(MutableTreeNode newChild, MutableTreeNode parent, int index) {
Item it = (Item) ((DefaultMutableTreeNode) newChild).getUserObject();
Group g = (Group) ((DefaultMutableTreeNode) parent).getUserObject();
extension.moveMenuItem(it.getId(), g.getId());
this.extension.moveMenuItem(it.getId(), g.getId());
super.insertNodeInto(newChild, parent, index);
extension.setChanged();
this.extension.setChanged();
}
 
@SuppressWarnings("rawtypes")
158,8 → 158,8
}
}
 
extension.renameMenuItem(previousId, newId);
extension.setChanged();
this.extension.renameMenuItem(previousId, newId);
this.extension.setChanged();
 
}
 
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/menu/mainmenu/MenuItemEditor.java
59,9 → 59,9
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;
c.gridwidth = 2;
textId = new JTextField();
this.textId = new JTextField();
 
this.add(textId, c);
this.add(this.textId, c);
c.gridy++;
 
c.gridwidth = 1;
72,13 → 72,13
c.gridx++;
 
c.fill = GridBagConstraints.HORIZONTAL;
comboActionType = new JComboBox();
this.comboActionType = new JComboBox();
 
this.add(comboActionType, c);
this.add(this.comboActionType, c);
c.gridx++;
c.weightx = 1;
comboActionChoice = new JComboBox();
this.add(comboActionChoice, c);
this.comboActionChoice = new JComboBox();
this.add(this.comboActionChoice, c);
 
c.gridy++;
}
87,9 → 87,9
c.gridx = 1;
c.weightx = 0;
c.fill = GridBagConstraints.NONE;
shownInMenu = new JCheckBox("Afficher dans le menu");
this.shownInMenu = new JCheckBox("Afficher dans le menu");
 
this.add(shownInMenu, c);
this.add(this.shownInMenu, c);
 
JPanel spacer = new JPanel();
c.gridx = 1;
100,9 → 100,9
initUIFrom(item.getId());
 
// Listeners
if (!isEditingGroup) {
if (!this.isEditingGroup) {
// comboActionType
comboActionType.addActionListener(new ActionListener() {
this.comboActionType.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
110,14 → 110,14
int type = cb.getSelectedIndex();
if (type == 0) {
// Saisie
comboActionChoice.setModel(new DefaultComboBoxModel(componentIds));
MenuItemEditor.this.comboActionChoice.setModel(new DefaultComboBoxModel(MenuItemEditor.this.componentIds));
 
MenuDescriptor desc = extension.getCreateMenuItemFromId(item.getId());
desc.setType(MenuDescriptor.CREATE);
desc.setListId(null);
if (componentIds.size() > 0) {
comboActionChoice.setSelectedIndex(0);
desc.setComponentId(comboActionChoice.getSelectedItem().toString());
if (MenuItemEditor.this.componentIds.size() > 0) {
MenuItemEditor.this.comboActionChoice.setSelectedIndex(0);
desc.setComponentId(MenuItemEditor.this.comboActionChoice.getSelectedItem().toString());
} else {
desc.setComponentId(null);
}
124,12 → 124,12
extension.setChanged();
} else {
// Liste
comboActionChoice.setModel(new DefaultComboBoxModel(listIds));
MenuItemEditor.this.comboActionChoice.setModel(new DefaultComboBoxModel(MenuItemEditor.this.listIds));
MenuDescriptor desc = extension.getCreateMenuItemFromId(item.getId());
desc.setType(MenuDescriptor.LIST);
if (listIds.size() > 0) {
comboActionChoice.setSelectedIndex(0);
desc.setListId(comboActionChoice.getSelectedItem().toString());
if (MenuItemEditor.this.listIds.size() > 0) {
MenuItemEditor.this.comboActionChoice.setSelectedIndex(0);
desc.setListId(MenuItemEditor.this.comboActionChoice.getSelectedItem().toString());
} else {
desc.setListId(null);
}
139,15 → 139,15
 
}
});
comboActionChoice.addActionListener(new ActionListener() {
this.comboActionChoice.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
MenuDescriptor desc = extension.getCreateMenuItemFromId(item.getId());
if (desc.getType().equals(MenuDescriptor.CREATE)) {
desc.setComponentId(comboActionChoice.getSelectedItem().toString());
desc.setComponentId(MenuItemEditor.this.comboActionChoice.getSelectedItem().toString());
} else if (desc.getType().equals(MenuDescriptor.LIST)) {
desc.setListId(comboActionChoice.getSelectedItem().toString());
desc.setListId(MenuItemEditor.this.comboActionChoice.getSelectedItem().toString());
} else {
desc.setComponentId(null);
desc.setListId(null);
156,13 → 156,13
});
 
}
shownInMenu.addActionListener(new ActionListener() {
this.shownInMenu.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
final boolean selected = shownInMenu.isSelected();
final boolean selected = MenuItemEditor.this.shownInMenu.isSelected();
 
treeModel.setActive(selected, item.getId());
MenuItemEditor.this.treeModel.setActive(selected, item.getId());
}
});
 
169,11 → 169,11
}
 
private void initUIFrom(String itemId) {
boolean hasCreated = extension.getCreateMenuItemFromId(itemId) != null;
textId.setEnabled(hasCreated);
previousId = itemId;
boolean hasCreated = this.extension.getCreateMenuItemFromId(itemId) != null;
this.textId.setEnabled(hasCreated);
this.previousId = itemId;
if (hasCreated) {
textId.getDocument().addDocumentListener(new DocumentListener() {
this.textId.getDocument().addDocumentListener(new DocumentListener() {
 
@Override
public void removeUpdate(DocumentEvent e) {
187,12 → 187,12
 
@Override
public void changedUpdate(DocumentEvent e) {
String t = textId.getText();
String t = MenuItemEditor.this.textId.getText();
System.err.println("MenuItemEditor.initUIFrom(...).new DocumentListener() {...}.changedUpdate()" + t);
 
if (!previousId.equals(t)) {
treeModel.renameMenuItem(previousId, t);
previousId = t;
if (!MenuItemEditor.this.previousId.equals(t)) {
MenuItemEditor.this.treeModel.renameMenuItem(MenuItemEditor.this.previousId, t);
MenuItemEditor.this.previousId = t;
 
}
}
199,59 → 199,59
});
}
 
shownInMenu.setSelected(extension.getRemoveMenuItemFromId(itemId) == null);
if (textId != null) {
textId.setText(itemId);
this.shownInMenu.setSelected(this.extension.getRemoveMenuItemFromId(itemId) == null);
if (this.textId != null) {
this.textId.setText(itemId);
}
if (!isEditingGroup) {
comboActionType.setEnabled(true);
comboActionChoice.setEnabled(true);
if (!this.isEditingGroup) {
this.comboActionType.setEnabled(true);
this.comboActionChoice.setEnabled(true);
final Action actionForId = MenuManager.getInstance().getActionForId(itemId);
if (hasCreated) {
MenuDescriptor desc = extension.getCreateMenuItemFromId(itemId);
comboActionType.setModel(new DefaultComboBoxModel(new String[] { "Saisie", "Liste" }));
MenuDescriptor desc = this.extension.getCreateMenuItemFromId(itemId);
this.comboActionType.setModel(new DefaultComboBoxModel(new String[] { "Saisie", "Liste" }));
//
final List<ComponentDescritor> compDescList = extension.getCreateComponentList();
componentIds = new Vector<String>(compDescList.size());
final List<ComponentDescritor> compDescList = this.extension.getCreateComponentList();
this.componentIds = new Vector<String>(compDescList.size());
for (ComponentDescritor componentDescritor : compDescList) {
final String id = componentDescritor.getId();
if (id != null) {
componentIds.add(id);
this.componentIds.add(id);
}
}
 
Collections.sort(componentIds);
Collections.sort(this.componentIds);
 
final List<ListDescriptor> listDescList = extension.getCreateListList();
listIds = new Vector<>(listDescList.size());
final List<ListDescriptor> listDescList = this.extension.getCreateListList();
this.listIds = new Vector<>(listDescList.size());
for (ListDescriptor listDescritor : listDescList) {
final String id = listDescritor.getId();
if (id != null) {
listIds.add(id);
this.listIds.add(id);
}
}
 
Collections.sort(listIds);
Collections.sort(this.listIds);
//
 
String type = desc.getType();
if (type.equals(MenuDescriptor.CREATE)) {
final String componentId = desc.getComponentId();
if (!componentIds.contains(componentId) && componentId != null) {
componentIds.add(componentId);
if (!this.componentIds.contains(componentId) && componentId != null) {
this.componentIds.add(componentId);
}
comboActionType.setSelectedIndex(0);
comboActionChoice.setModel(new DefaultComboBoxModel(componentIds));
comboActionChoice.setSelectedItem(componentId);
this.comboActionType.setSelectedIndex(0);
this.comboActionChoice.setModel(new DefaultComboBoxModel(this.componentIds));
this.comboActionChoice.setSelectedItem(componentId);
 
} else if (type.equals(MenuDescriptor.LIST)) {
final String listId = desc.getListId();
if (!listIds.contains(listId) && listId != null) {
listIds.add(listId);
if (!this.listIds.contains(listId) && listId != null) {
this.listIds.add(listId);
}
comboActionType.setSelectedIndex(1);
comboActionChoice.setModel(new DefaultComboBoxModel(listIds));
comboActionChoice.setSelectedItem(listId);
this.comboActionType.setSelectedIndex(1);
this.comboActionChoice.setModel(new DefaultComboBoxModel(this.listIds));
this.comboActionChoice.setSelectedItem(listId);
 
} else {
throw new IllegalArgumentException("Unknown type " + type);
263,14 → 263,14
JFrame frame = a.createFrame();
if (frame != null) {
if (frame instanceof EditFrame) {
comboActionType.setModel(new DefaultComboBoxModel(new String[] { "Saisie" }));
this.comboActionType.setModel(new DefaultComboBoxModel(new String[] { "Saisie" }));
} else if (frame instanceof IListFrame) {
comboActionType.setModel(new DefaultComboBoxModel(new String[] { "Liste" }));
this.comboActionType.setModel(new DefaultComboBoxModel(new String[] { "Liste" }));
} else {
comboActionType.setModel(new DefaultComboBoxModel(new String[] { "Autre" }));
this.comboActionType.setModel(new DefaultComboBoxModel(new String[] { "Autre" }));
}
 
comboActionChoice.setModel(new DefaultComboBoxModel(new String[] { frame.getTitle() }));
this.comboActionChoice.setModel(new DefaultComboBoxModel(new String[] { frame.getTitle() }));
} else {
comboActionType.setModel(new DefaultComboBoxModel(new String[] { "Autre" }));
comboActionChoice.setModel(new DefaultComboBoxModel(new String[] { actionForId.getClass().getName() }));
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/menu/MenuCreateMainPanel.java
9,12 → 9,12
 
public MenuCreateMainPanel(Extension extension) {
super(extension);
split.setDividerLocation(0.5D);
this.split.setDividerLocation(0.5D);
}
 
@Override
public JComponent createLeftComponent() {
return new MenuListPanel(extension, this);
return new MenuListPanel(this.extension, this);
}
 
 
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/ExtensionListPanel.java
18,10 → 18,10
}
this.extensionBuilderModule = extensionBuilderModule;
this.setLayout(new GridLayout(1, 1));
newLeftComponent = new ExtensionMainListPanel(this);
this.split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, newLeftComponent, rPanel);
this.newLeftComponent = new ExtensionMainListPanel(this);
this.split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, this.newLeftComponent, this.rPanel);
this.add(this.split);
newLeftComponent.fill();
this.newLeftComponent.fill();
}
 
public void setRightPanel(JComponent p) {
32,11 → 32,11
}
 
public ExtensionBuilderModule getExtensionBuilderModule() {
return extensionBuilderModule;
return this.extensionBuilderModule;
}
 
public void modelChanged() {
newLeftComponent.modelChanged();
this.newLeftComponent.modelChanged();
}
 
}
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/ExtensionBuilderModule.java
89,7 → 89,7
}
Log.get().info("setupMenu");
// Start previously started extensions
for (Extension extension : extensions) {
for (Extension extension : this.extensions) {
if (extension.isAutoStart()) {
try {
extension.setupMenu(ctxt);
108,7 → 108,7
final DBRoot root = ComptaPropsConfiguration.getInstanceCompta().getRootSociete();
 
// Start previously started extensions
for (Extension extension : extensions) {
for (Extension extension : this.extensions) {
if (extension.isAutoStart()) {
try {
extension.start(root, true);
124,7 → 124,7
 
@Override
protected void stop() {
for (Extension extension : extensions) {
for (Extension extension : this.extensions) {
extension.stop();
}
this.extensions.clear();
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/ExtensionListModel.java
17,7 → 17,7
}
 
public void fill(final EditableListPanel list) {
addAll(moduleListPanel.getExtensionBuilderModule().getExtensions());
addAll(this.moduleListPanel.getExtensionBuilderModule().getExtensions());
final int size = this.getSize();
if (size > 0) {
final Object firstElement = firstElement();
39,7 → 39,7
@Override
public void addElement(Object obj) {
final Extension e = (Extension) obj;
moduleListPanel.getExtensionBuilderModule().add(e);
this.moduleListPanel.getExtensionBuilderModule().add(e);
e.addChangeListener(this);
super.addElement(obj);
}
49,7 → 49,7
final Extension extenstion = (Extension) obj;
final int answer = JOptionPane.showConfirmDialog(new JFrame(), "Voulez vous vraiment supprimer l'extension " + extenstion.getName() + " ?", "Suppression", JOptionPane.YES_NO_OPTION);
if (answer == JOptionPane.OK_OPTION) {
moduleListPanel.getExtensionBuilderModule().remove(extenstion);
this.moduleListPanel.getExtensionBuilderModule().remove(extenstion);
extenstion.removeChangeListener(this);
return super.removeElement(obj);
}
58,7 → 58,7
 
@Override
public void stateChanged(ChangeEvent e) {
moduleListPanel.modelChanged();
this.moduleListPanel.modelChanged();
}
 
}
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/list/ListCreatePanel.java
38,16 → 38,16
c.weighty = 1;
c.gridwidth = 2;
c.fill = GridBagConstraints.BOTH;
panel = new FieldDescSelector(n, extension);
this.panel = new FieldDescSelector(n, extension);
final String mainTable = n.getMainTable();
if (mainTable == null && comboTable.getModel().getSize() > 0) {
comboTable.setSelectedIndex(0);
panel.setMainTable((String) comboTable.getModel().getElementAt(0));
this.panel.setMainTable((String) comboTable.getModel().getElementAt(0));
} else {
comboTable.setSelectedItem(mainTable);
panel.setMainTable(mainTable);
this.panel.setMainTable(mainTable);
}
this.add(panel, c);
this.add(this.panel, c);
 
comboTable.addActionListener(new ActionListener() {
 
54,7 → 54,7
@Override
public void actionPerformed(ActionEvent e) {
n.removeAllColumns();
panel.setMainTable((String) comboTable.getSelectedItem());
ListCreatePanel.this.panel.setMainTable((String) comboTable.getSelectedItem());
extension.setChanged();
}
});
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/list/FieldDescSelector.java
9,6 → 9,7
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
 
import javax.swing.DefaultListCellRenderer;
import javax.swing.ImageIcon;
46,8 → 47,8
// Col 0
c.gridx = 0;
c.gridy++;
treeModel = new FieldTreeModel(extension);
this.tree = new JTree(treeModel) {
this.treeModel = new FieldTreeModel(extension);
this.tree = new JTree(this.treeModel) {
@Override
public String convertValueToText(Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
final Object userObject = ((DefaultMutableTreeNode) value).getUserObject();
61,19 → 62,19
return " " + d.getName();
}
};
tree.setRootVisible(false);
tree.setShowsRootHandles(true);
this.tree.setRootVisible(false);
this.tree.setShowsRootHandles(true);
final DefaultTreeCellRenderer treeRenderer = new DefaultTreeCellRenderer();
 
treeRenderer.setLeafIcon(null);
treeRenderer.setOpenIcon(new ImageIcon(this.getClass().getResource("ref.png")));
treeRenderer.setClosedIcon(new ImageIcon(this.getClass().getResource("ref.png")));
tree.setCellRenderer(treeRenderer);
this.tree.setCellRenderer(treeRenderer);
c.gridheight = 2;
c.weightx = 1;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
this.add(new JScrollPane(tree), c);
this.add(new JScrollPane(this.tree), c);
// Col 1
c.gridx = 1;
c.gridheight = 1;
93,7 → 94,7
c.weightx = 1;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
listModel = new DefaultListModel() {
this.listModel = new DefaultListModel() {
@Override
public void addElement(Object obj) {
if (!(obj instanceof ColumnDescriptor)) {
103,9 → 104,9
}
 
};
list = new ReorderableJList();
list.setModel(listModel);
list.setCellRenderer(new DefaultListCellRenderer() {
this.list = new ReorderableJList();
this.list.setModel(this.listModel);
this.list.setCellRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
ColumnDescriptor f = (ColumnDescriptor) value;
113,9 → 114,9
return super.getListCellRendererComponent(list, label, index, isSelected, cellHasFocus);
}
});
this.add(new JScrollPane(list), c);
this.add(new JScrollPane(this.list), c);
// Listeners
tree.addMouseListener(new MouseAdapter() {
this.tree.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() > 1) {
140,7 → 141,7
 
}
});
list.addKeyListener(new KeyAdapter() {
this.list.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_DELETE) {
154,8 → 155,8
 
public void setMainTable(String table) {
this.listDescriptor.setMainTable(table);
treeModel.fillFromTable(table);
listModel.removeAllElements();
this.treeModel.fillFromTable(table);
this.listModel.removeAllElements();
for (ColumnDescriptor d : this.listDescriptor.getColumns()) {
this.listModel.addElement(d);
}
162,18 → 163,24
}
 
private void deleteSelectedInList() {
Object[] vals = list.getSelectedValues();
if (vals == null)
List<Object> vals = this.list.getSelectedValuesList();
if (vals.isEmpty())
return;
for (int i = 0; i < vals.length; i++) {
Object object = vals[i];
this.listModel.removeElement(object);
for (Object object : vals) {
boolean b = this.listModel.removeElement(object);
if (!b) {
throw new IllegalStateException("cannot remove " + object + " from list model " + this.listModel);
}
if (object instanceof ColumnDescriptor) {
ColumnDescriptor c = (ColumnDescriptor) object;
this.listDescriptor.remove(c);
}
}
list.clearSelection();
this.list.clearSelection();
}
 
private void addTreeSelectionToList() {
final TreePath[] paths = tree.getSelectionPaths();
final TreePath[] paths = this.tree.getSelectionPaths();
if (paths == null)
return;
for (int i = 0; i < paths.length; i++) {
203,10 → 210,10
if (d != null && root != null) {
boolean add = true;
final String extendedLabel = root.getPath();
final int size = listModel.getSize();
final int size = this.listModel.getSize();
// Check if already in the list
for (int j = 0; j < size; j++) {
if (((ColumnDescriptor) listModel.getElementAt(j)).getFieldsPaths().contains(extendedLabel)) {
if (((ColumnDescriptor) this.listModel.getElementAt(j)).getFieldsPaths().contains(extendedLabel)) {
add = false;
break;
}
214,12 → 221,12
if (add) {
final ColumnDescriptor colDesc = new ColumnDescriptor(root.getPath());
colDesc.setFieldsPaths(root.getPath());
listModel.addElement(colDesc);
listDescriptor.add(colDesc);
this.listModel.addElement(colDesc);
this.listDescriptor.add(colDesc);
}
}
}
tree.clearSelection();
this.tree.clearSelection();
}
 
}
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/list/FieldTreeModel.java
80,7 → 80,7
newChild.setAllowsChildren(false);
}
}
this.setRoot(root);
this.setRoot(this.root);
}
}
 
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/list/ListCreateMainPanel.java
13,7 → 13,7
 
@Override
public JComponent createLeftComponent() {
return new ListListPanel(extension, this);
return new ListListPanel(this.extension, this);
}
 
public void select(ListDescriptor listDescriptor) {
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/list/EditableListPanel.java
43,9 → 43,9
if (title != null) {
this.add(new JLabel(title), c);
}
list = new JList(dataModel);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final JScrollPane comp2 = new JScrollPane(list);
this.list = new JList(dataModel);
this.list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final JScrollPane comp2 = new JScrollPane(this.list);
comp2.setMinimumSize(new Dimension(150, 150));
comp2.setPreferredSize(new Dimension(150, 150));
c.weighty = 1;
64,15 → 64,15
this.add(addButton, c);
c.gridy++;
if (canRename) {
renameButton = new JButton("Renommer");
this.add(renameButton, c);
renameButton.setEnabled(false);
renameButton.addActionListener(new ActionListener() {
this.renameButton = new JButton("Renommer");
this.add(this.renameButton, c);
this.renameButton.setEnabled(false);
this.renameButton.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
if (list.getSelectedValue() != null) {
renameItem(list.getSelectedValue());
if (EditableListPanel.this.list.getSelectedValue() != null) {
renameItem(EditableListPanel.this.list.getSelectedValue());
}
}
 
80,9 → 80,9
c.gridy++;
}
 
removeButton = new JButton("Supprimer");
removeButton.setEnabled(false);
this.add(removeButton, c);
this.removeButton = new JButton("Supprimer");
this.removeButton.setEnabled(false);
this.add(this.removeButton, c);
 
// init
 
98,25 → 98,25
 
});
 
removeButton.addActionListener(new ActionListener() {
this.removeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (list.getSelectedValue() != null) {
removeItem(list.getSelectedValue());
if (EditableListPanel.this.list.getSelectedValue() != null) {
removeItem(EditableListPanel.this.list.getSelectedValue());
}
}
});
}
list.addListSelectionListener(new ListSelectionListener() {
this.list.addListSelectionListener(new ListSelectionListener() {
 
@Override
public void valueChanged(ListSelectionEvent e) {
final Object selectedValue = list.getSelectedValue();
if (removeButton != null) {
removeButton.setEnabled(selectedValue != null);
final Object selectedValue = EditableListPanel.this.list.getSelectedValue();
if (EditableListPanel.this.removeButton != null) {
EditableListPanel.this.removeButton.setEnabled(selectedValue != null);
}
if (renameButton != null) {
renameButton.setEnabled(selectedValue != null);
if (EditableListPanel.this.renameButton != null) {
EditableListPanel.this.renameButton.setEnabled(selectedValue != null);
}
if (!e.getValueIsAdjusting() && selectedValue != null) {
 
136,7 → 136,7
* Select an item in the list
* */
public void selectItem(Object item) {
list.setSelectedValue(item, true);
this.list.setSelectedValue(item, true);
}
 
/**
162,7 → 162,7
public abstract void itemSelected(Object item);
 
public void reload() {
list.invalidate();
list.repaint();
this.list.invalidate();
this.list.repaint();
}
}
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/list/ListListPanel.java
21,7 → 21,7
 
@Override
public void addNewItem() {
((CreateListListModel) dataModel).addNewList();
((CreateListListModel) this.dataModel).addNewList();
}
 
@Override
36,8 → 36,8
 
@Override
public void removeItem(Object item) {
((CreateListListModel) dataModel).removeElement(item);
extension.removeCreateList((ListDescriptor) item);
((CreateListListModel) this.dataModel).removeElement(item);
this.extension.removeCreateList((ListDescriptor) item);
}
 
@Override
44,10 → 44,10
public void itemSelected(Object item) {
if (item != null) {
ListDescriptor n = (ListDescriptor) item;
final ListCreatePanel p = new ListCreatePanel(n, extension);
tableInfoPanel.setRightPanel(p);
final ListCreatePanel p = new ListCreatePanel(n, this.extension);
this.tableInfoPanel.setRightPanel(p);
} else {
tableInfoPanel.setRightPanel(new JPanel());
this.tableInfoPanel.setRightPanel(new JPanel());
}
}
}
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/list/ListDescriptor.java
15,7 → 15,7
}
 
public String getId() {
return id;
return this.id;
}
 
public void setId(String id) {
27,11 → 27,11
}
 
public String getMainTable() {
return mainTable;
return this.mainTable;
}
 
public List<ColumnDescriptor> getColumns() {
return columns;
return this.columns;
}
 
@Override
51,4 → 51,8
public void removeAllColumns() {
this.columns.clear();
}
 
public void remove(ColumnDescriptor c) {
this.columns.remove(c);
}
}
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/list/ColumnDescriptor.java
15,14 → 15,14
}
 
public String getId() {
return id;
return this.id;
}
 
public String getFieldsPaths() {
String r = "";
final int size = fieldPaths.size();
final int size = this.fieldPaths.size();
for (int i = 0; i < size; i++) {
String fieldPath = fieldPaths.get(i);
String fieldPath = this.fieldPaths.get(i);
if (i != 0) {
r += ",";
}
33,14 → 33,14
 
public void setFieldsPaths(String paths) {
final List<String> l = StringUtils.fastSplit(paths, ',');
fieldPaths.clear();
this.fieldPaths.clear();
for (String string : l) {
fieldPaths.add(string.trim());
this.fieldPaths.add(string.trim());
}
}
 
public String getStyle() {
return style;
return this.style;
}
 
public void setStyle(String style) {
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/list/CreateListListModel.java
17,7 → 17,7
}
 
private void addContent() {
this.addAll(extension.getCreateListList());
this.addAll(this.extension.getCreateListList());
}
 
@Override
28,11 → 28,11
 
public void addNewList() {
final ListDescriptor l = new ListDescriptor("liste " + (this.getSize() + 1));
final List<String> allKnownTableNames = extension.getAllKnownTableNames();
final List<String> allKnownTableNames = this.extension.getAllKnownTableNames();
final String mainTable = allKnownTableNames.get(0);
l.setMainTable(mainTable);
this.addElement(l);
extension.addCreateList(l);
this.extension.addCreateList(l);
}
 
}
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/AbstractSplittedPanel.java
15,14 → 15,14
this.extension = extension;
this.setLayout(new GridLayout(1, 1));
this.setOpaque(false);
leftComponent = createLeftComponent();
split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftComponent, new JPanel());
this.add(split);
this.leftComponent = createLeftComponent();
this.split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, this.leftComponent, new JPanel());
this.add(this.split);
}
 
public void setRightPanel(JComponent p) {
this.invalidate();
split.setRightComponent(p);
this.split.setRightComponent(p);
this.revalidate();
this.repaint();
}
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/ExtensionMainListPanel.java
22,6 → 22,7
this.moduleListPanel = moduleListPanel;
this.list.setFixedCellHeight(new JLabel("A").getPreferredSize().height + 8);
this.list.setCellRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
final JLabel listCellRendererComponent = (JLabel) super.getListCellRendererComponent(list, ((Extension) value).getName(), index, isSelected, cellHasFocus);
Extension e = (Extension) value;
35,13 → 36,13
}
 
public void fill() {
((ExtensionListModel) dataModel).fill(this);
((ExtensionListModel) this.dataModel).fill(this);
 
}
 
@Override
public void addNewItem() {
((ExtensionListModel) dataModel).addNewModule();
((ExtensionListModel) this.dataModel).addNewModule();
}
 
@Override
56,22 → 57,22
 
@Override
public void removeItem(Object item) {
((ExtensionListModel) dataModel).removeElement(item);
((ExtensionListModel) this.dataModel).removeElement(item);
}
 
@Override
public void itemSelected(Object item) {
if (item != null) {
final ExtensionInfoPanel p = new ExtensionInfoPanel((Extension) item, moduleListPanel);
moduleListPanel.setRightPanel(p);
final ExtensionInfoPanel p = new ExtensionInfoPanel((Extension) item, this.moduleListPanel);
this.moduleListPanel.setRightPanel(p);
} else {
moduleListPanel.setRightPanel(new JPanel());
this.moduleListPanel.setRightPanel(new JPanel());
}
 
}
 
public void modelChanged() {
list.invalidate();
list.repaint();
this.list.invalidate();
this.list.repaint();
}
}
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/meu/actions/ActionMainPanel.java
13,6 → 13,6
 
@Override
public JComponent createLeftComponent() {
return new ActionListPanel(extension, this);
return new ActionListPanel(this.extension, this);
}
}
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/meu/actions/ActionItemEditor.java
44,8 → 44,8
 
c.weightx = 1;
 
textId = new JTextField();
this.add(textId, c);
this.textId = new JTextField();
this.add(this.textId, c);
 
//
final List<ComponentDescritor> l = extension.getCreateComponentList();
63,16 → 63,18
c.fill = GridBagConstraints.HORIZONTAL;
this.add(new JLabel("Composant", SwingConstants.RIGHT), c);
c.gridx++;
comboComponent = new JComboBox(v);
comboComponent.setRenderer(new DefaultListCellRenderer() {
this.comboComponent = new JComboBox(v);
this.comboComponent.setRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
value = ((ComponentDescritor) value).getId();
if (value != null) {
value = ((ComponentDescritor) value).getId();
}
return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
}
});
c.fill = GridBagConstraints.NONE;
this.add(comboComponent, c);
this.add(this.comboComponent, c);
 
c.gridx = 0;
c.gridy++;
81,9 → 83,9
this.add(new JLabel("Table", SwingConstants.RIGHT), c);
c.gridx++;
c.fill = GridBagConstraints.NONE;
textTable = new JTextField(30);
textTable.setEnabled(false);
this.add(textTable, c);
this.textTable = new JTextField(30);
this.textTable.setEnabled(false);
this.add(this.textTable, c);
// Location
c.gridx = 0;
c.gridy++;
92,8 → 94,8
this.add(new JLabel("Emplacement", SwingConstants.RIGHT), c);
c.gridx++;
c.fill = GridBagConstraints.NONE;
comboLocation = new JComboBox(new String[] { "Bouton et clic droit", "clic droit uniquement", "bouton uniquement" });
this.add(comboLocation, c);
this.comboLocation = new JComboBox(new String[] { "Bouton et clic droit", "clic droit uniquement", "bouton uniquement" });
this.add(this.comboLocation, c);
c.gridy++;
c.weighty = 1;
this.add(new JPanel(), c);
100,25 → 102,25
 
initUIFrom(actionDescriptor);
 
comboComponent.addActionListener(new ActionListener() {
this.comboComponent.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
final ComponentDescritor componentDescritor = getComponentDescritor(comboComponent.getSelectedItem().toString());
final ComponentDescritor componentDescritor = getComponentDescritor(ActionItemEditor.this.comboComponent.getSelectedItem().toString());
if (componentDescritor != null) {
textTable.setText(componentDescritor.getTable());
ActionItemEditor.this.textTable.setText(componentDescritor.getTable());
actionDescriptor.setComponentId(componentDescritor.getId());
actionDescriptor.setTable(componentDescritor.getTable());
} else {
textTable.setText("");
ActionItemEditor.this.textTable.setText("");
}
}
});
comboLocation.addActionListener(new ActionListener() {
this.comboLocation.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
int index = comboLocation.getSelectedIndex();
int index = ActionItemEditor.this.comboLocation.getSelectedIndex();
if (index == 0) {
actionDescriptor.setLocation(ActionDescriptor.LOCATION_HEADER_POPUP);
} else if (index == 1) {
129,7 → 131,7
 
}
});
textId.getDocument().addDocumentListener(new DocumentListener() {
this.textId.getDocument().addDocumentListener(new DocumentListener() {
 
@Override
public void removeUpdate(DocumentEvent e) {
145,7 → 147,7
 
@Override
public void changedUpdate(DocumentEvent e) {
actionDescriptor.setId(textId.getText());
actionDescriptor.setId(ActionItemEditor.this.textId.getText());
}
});
 
153,24 → 155,24
 
private void initUIFrom(ActionDescriptor item) {
 
textId.setText(item.getId());
this.textId.setText(item.getId());
final ComponentDescritor componentDescritor = getComponentDescritor(item.getComponentId());
if (componentDescritor != null) {
comboComponent.setSelectedItem(componentDescritor);
this.comboComponent.setSelectedItem(componentDescritor);
}
textTable.setText(item.getTable());
this.textTable.setText(item.getTable());
String loc = item.getLocation();
if (loc.equals(ActionDescriptor.LOCATION_HEADER_POPUP)) {
comboLocation.setSelectedIndex(0);
this.comboLocation.setSelectedIndex(0);
} else if (loc.equals(ActionDescriptor.LOCATION_HEADER)) {
comboLocation.setSelectedIndex(2);
this.comboLocation.setSelectedIndex(2);
} else {
comboLocation.setSelectedIndex(1);
this.comboLocation.setSelectedIndex(1);
}
}
 
private ComponentDescritor getComponentDescritor(String componentId) {
List<ComponentDescritor> l = extension.getCreateComponentList();
List<ComponentDescritor> l = this.extension.getCreateComponentList();
for (ComponentDescritor componentDescritor : l) {
if (componentDescritor.getId().equals(componentId)) {
return componentDescritor;
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/meu/actions/AllKnownActionsListModel.java
6,9 → 6,18
import org.openconcerto.ui.DefaultListModel;
 
public class AllKnownActionsListModel extends DefaultListModel {
private final Extension extension;
 
public AllKnownActionsListModel(Extension module) {
List<ActionDescriptor> l = module.getActionDescriptors();
public AllKnownActionsListModel(Extension extension) {
final List<ActionDescriptor> l = extension.getActionDescriptors();
this.addAll(l);
this.extension = extension;
}
 
public void addAction() {
final ActionDescriptor obj = new ActionDescriptor("Action_" + this.size());
this.addElement(obj);
this.extension.addCreateAction(obj);
 
}
}
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/meu/actions/ActionListPanel.java
15,14 → 15,14
 
public class ActionListPanel extends EditableListPanel {
 
private ActionMainPanel tableTranslationPanel;
private ActionMainPanel actionPanel;
private Extension extension;
 
public ActionListPanel(Extension extension, ActionMainPanel tableTranslationPanel) {
super(new AllKnownActionsListModel(extension), "Actions", "", true, true);
public ActionListPanel(Extension extension, ActionMainPanel actionPanel) {
super(new AllKnownActionsListModel(extension), "Actions", "Ajouter une action", true, true);
this.extension = extension;
this.tableTranslationPanel = tableTranslationPanel;
list.setCellRenderer(new DefaultListCellRenderer() {
this.actionPanel = actionPanel;
this.list.setCellRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
value = ((ActionDescriptor) value).getId();
33,9 → 33,16
 
@Override
public void addNewItem() {
((AllKnownActionsListModel) this.dataModel).addAction();
}
 
@Override
public void removeItem(Object item) {
((AllKnownActionsListModel) this.dataModel).removeElement(item);
this.extension.removeCreateAction((ActionDescriptor) item);
}
 
@Override
public void renameItem(Object item) {
final ActionDescriptor e = (ActionDescriptor) item;
final Window w = SwingUtilities.windowForComponent(this);
42,19 → 49,16
final String s = (String) JOptionPane.showInputDialog(w, "Nouveau nom", "Renommer la liste", JOptionPane.PLAIN_MESSAGE, null, null, e.getId());
if ((s != null) && (s.length() > 0)) {
e.setId(s);
reload();
}
}
 
@Override
public void removeItem(Object item) {
}
 
@Override
public void itemSelected(Object item) {
if (item != null) {
tableTranslationPanel.setRightPanel(new JScrollPane(new ActionItemEditor((ActionDescriptor) item, extension)));
this.actionPanel.setRightPanel(new JScrollPane(new ActionItemEditor((ActionDescriptor) item, this.extension)));
} else {
tableTranslationPanel.setRightPanel(new JPanel());
this.actionPanel.setRightPanel(new JPanel());
}
}
 
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/meu/actions/ActionDescriptor.java
3,9 → 3,9
public class ActionDescriptor {
 
private String id;
private String location; // header, popup, both
private String table;
private String componentId;
private String location = LOCATION_HEADER_POPUP; // header, popup, both
private String table = "";
private String componentId = "";
public static final String LOCATION_HEADER = "header";
public static final String LOCATION_POPUP = "popup";
public static final String LOCATION_HEADER_POPUP = "header,popup";
15,7 → 15,7
}
 
public String getId() {
return id;
return this.id;
}
 
public void setId(String id) {
23,7 → 23,7
}
 
public String getLocation() {
return location;
return this.location;
}
 
public void setLocation(String location) {
31,7 → 31,7
}
 
public String getTable() {
return table;
return this.table;
}
 
public void setTable(String table) {
39,7 → 39,7
}
 
public String getComponentId() {
return componentId;
return this.componentId;
}
 
public void setComponentId(String componentId) {
46,4 → 46,11
this.componentId = componentId;
}
 
@Override
public boolean equals(Object obj) {
if (obj instanceof ActionDescriptor) {
return this.id.equals(((ActionDescriptor) obj).id);
}
return super.equals(obj);
}
}
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/table/TableDescritor.java
36,9 → 36,9
// Create elements
ComptaPropsConfiguration conf = ComptaPropsConfiguration.getInstanceCompta();
DBRoot root = conf.getRootSociete();
if (conf.getDirectory().getElement(name) == null) {
final SQLTable table = root.getTable(name);
final SQLElement e = new SQLElement("ext." + name, "ext." + name, table) {
if (conf.getDirectory().getElement(this.name) == null) {
final SQLTable table = root.getTable(this.name);
final SQLElement e = new SQLElement("ext." + this.name, "ext." + this.name, table) {
 
@Override
protected List<String> getListFields() {
60,6 → 60,7
l.add("NOM");
} else {
ListDescriptor listDesc = null;
l.clear();
for (ListDescriptor listDescriptor : ext.getCreateListList()) {
if (listDescriptor.getMainTable().equals(getTable().getName())) {
listDesc = listDescriptor;
66,12 → 67,19
break;
}
}
for (ColumnDescriptor string : listDesc.getColumns()) {
if (!string.getFieldsPaths().contains(".")) {
l.add(string.getFieldsPaths());
break;
if (listDesc != null) {
for (ColumnDescriptor string : listDesc.getColumns()) {
if (!string.getFieldsPaths().contains(".")) {
l.add(string.getFieldsPaths());
break;
}
}
}
if (l.isEmpty()) {
if (!getTable().getContentFields().isEmpty()) {
l.add(new ArrayList<>(getTable().getContentFields()).get(0).getName());
}
}
}
return l;
}
101,7 → 109,7
return new ExtensionGroupSQLComponent(this, cDescriptor.getGroup());
}
}
JOptionPane.showMessageDialog(new JFrame(), "Unable to create default creation component for table " + name);
JOptionPane.showMessageDialog(new JFrame(), "Unable to create default creation component for table " + TableDescritor.this.name);
return null;
}
};
111,7 → 119,7
}
 
public String getName() {
return name;
return this.name;
}
 
public void setName(String name) {
119,22 → 127,22
}
 
public List<FieldDescriptor> getFields() {
return fields;
return this.fields;
}
 
public void add(FieldDescriptor f) {
fields.add(f);
this.fields.add(f);
 
}
 
public void remove(FieldDescriptor field) {
fields.remove(field);
this.fields.remove(field);
 
}
 
@Override
public String toString() {
return name;
return this.name;
}
 
public void sortFields() {
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/table/TableMainPanel.java
14,14 → 14,14
public TableMainPanel(Extension extension) {
this.setLayout(new GridLayout(1, 1));
JTabbedPane tab = new JTabbedPane();
component = new TableCreateMainPanel(extension);
tab.addTab("Tables créées par l'extension", component);
this.component = new TableCreateMainPanel(extension);
tab.addTab("Tables créées par l'extension", this.component);
tab.addTab("Tables modifiées", new TableModifyMainPanel(extension));
this.add(tab);
}
 
public void select(TableDescritor tableDescriptor) {
component.select(tableDescriptor);
this.component.select(tableDescriptor);
 
}
 
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/table/TableModifyPanel.java
88,7 → 88,7
private void addField(final TableDescritor desc, final JPanel p, GridBagConstraints c, final FieldDescriptor field) {
c.weightx = 1;
c.gridx = 0;
final FieldDescriptorEditor editor = new FieldDescriptorEditor(extension, field);
final FieldDescriptorEditor editor = new FieldDescriptorEditor(this.extension, field);
p.add(editor, c);
 
c.gridx++;
104,7 → 104,7
p.remove(editor);
p.remove(close);
p.revalidate();
extension.setChanged();
TableModifyPanel.this.extension.setChanged();
}
});
c.gridy++;
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/table/FieldDescriptor.java
39,14 → 39,14
@Override
public String toString() {
String string = this.table + " " + this.name + " type:" + this.type + " default:" + this.defaultValue + " l:" + this.length + " t:" + this.foreignTable;
if (link != null) {
string += " => " + link.toString();
if (this.link != null) {
string += " => " + this.link.toString();
}
return string;
}
 
public String getName() {
return name;
return this.name;
}
 
public void setName(String name) {
54,7 → 54,7
}
 
public String getType() {
return type;
return this.type;
}
 
public void setType(String type) {
62,7 → 62,7
}
 
public String getDefaultValue() {
return defaultValue;
return this.defaultValue;
}
 
public void setDefaultValue(String defaultValue) {
70,7 → 70,7
}
 
public String getLength() {
return length;
return this.length;
}
 
public void setLength(String length) {
78,7 → 78,7
}
 
public String getTable() {
return table;
return this.table;
}
 
public void setLink(FieldDescriptor fieldDescriptor) {
86,7 → 86,7
}
 
public FieldDescriptor getLink() {
return link;
return this.link;
}
 
public void setForeignTable(String foreignTable) {
94,7 → 94,7
}
 
public String getForeignTable() {
return foreignTable;
return this.foreignTable;
}
 
public String getExtendedLabel() {
111,8 → 111,8
public boolean equals(Object obj) {
if (obj instanceof FieldDescriptor) {
FieldDescriptor f = (FieldDescriptor) obj;
if (getTable().equals(f.getTable()) && getName().equals(f.getTable())) {
return getLink() != null && getLink().equals(f.getLink());
if (getTable().equals(f.getTable()) && getName().equals(f.getName())) {
return (getLink() == null && f.getLink() == null) || (getLink() != null && getLink().equals(f.getLink()));
} else {
return false;
}
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/table/TableModifyMainPanel.java
14,13 → 14,13
public TableModifyMainPanel(Extension extension) {
this.setLayout(new GridLayout(1, 1));
final TableModifyLeftPanel newLeftComponent = new TableModifyLeftPanel(extension, this);
split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, newLeftComponent, new JPanel());
this.add(split);
this.split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, newLeftComponent, new JPanel());
this.add(this.split);
}
 
public void setRightPanel(JComponent p) {
this.invalidate();
split.setRightComponent(p);
this.split.setRightComponent(p);
this.revalidate();
this.repaint();
}
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/table/CreateTableListModel.java
30,18 → 30,18
// FIXME: ensure table does not exists
final TableDescritor obj = new TableDescritor("TABLE_" + this.size());
this.addElement(obj);
extension.addCreateTable(obj);
this.extension.addCreateTable(obj);
}
 
@Override
public boolean removeElement(Object obj) {
extension.removeCreateTable((TableDescritor) obj);
this.extension.removeCreateTable((TableDescritor) obj);
return super.removeElement(obj);
}
 
@Override
public void stateChanged(ChangeEvent e) {
this.loadContent(extension);
this.loadContent(this.extension);
}
 
}
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/table/ElementDescriptor.java
10,15 → 10,15
}
 
public String getId() {
return id;
return this.id;
}
 
public String getTableName() {
return tableName;
return this.tableName;
}
 
@Override
public String toString() {
return "ElementDescriptor id: " + id + " table: " + tableName;
return "ElementDescriptor id: " + this.id + " table: " + this.tableName;
}
}
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/table/FieldDescriptorEditor.java
1,16 → 1,22
package org.openconcerto.modules.extensionbuilder.table;
 
import java.awt.Color;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import java.util.Vector;
 
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
54,30 → 60,30
this.add(new JLabel("Type"), c);
c.gridx++;
 
comboType = new JComboBox(types);
comboType.setOpaque(false);
this.add(comboType, c);
this.comboType = new JComboBox(this.types);
this.comboType.setOpaque(false);
this.add(this.comboType, c);
c.gridx++;
this.add(new JLabel("Nom"), c);
c.gridx++;
c.weightx = 1;
fieldName = new JTextField(10);
this.add(fieldName, c);
this.fieldName = new JTextField(10);
this.add(this.fieldName, c);
c.weightx = 0;
c.gridx++;
labelOption = new JLabel("Longeur max");
this.add(labelOption, c);
this.labelOption = new JLabel("Longeur max");
this.add(this.labelOption, c);
c.gridx++;
textOption = new JTextField(6);
this.textOption = new JTextField(6);
c.gridx++;
this.add(textOption, c);
comboOption = new JComboBox();
this.add(this.textOption, c);
this.comboOption = new JComboBox();
 
this.add(comboOption, c);
this.add(this.comboOption, c);
 
updateFrom(fd);
comboType.addActionListener(this);
fieldName.getDocument().addDocumentListener(new DocumentListener() {
this.comboType.addActionListener(this);
this.fieldName.getDocument().addDocumentListener(new DocumentListener() {
 
@Override
public void removeUpdate(DocumentEvent e) {
97,8 → 103,8
 
}
});
comboOption.addActionListener(this);
textOption.getDocument().addDocumentListener(new DocumentListener() {
this.comboOption.addActionListener(this);
this.textOption.getDocument().addDocumentListener(new DocumentListener() {
 
@Override
public void removeUpdate(DocumentEvent e) {
125,7 → 131,7
if (text.trim().length() > 0) {
this.fd.setName(text);
}
extension.setChanged();
this.extension.setChanged();
 
}
 
136,128 → 142,127
switch (this.comboType.getSelectedIndex()) {
 
case TYPE_STRING:
fd.setLength(text);
fd.setDefaultValue(null);
fd.setForeignTable(null);
fd.setLink(null);
this.fd.setLength(text);
this.fd.setDefaultValue(null);
this.fd.setForeignTable(null);
this.fd.setLink(null);
break;
case TYPE_INTEGER:
fd.setLength(null);
this.fd.setLength(null);
try {
int i = Integer.parseInt(text);
fd.setDefaultValue(text);
this.fd.setDefaultValue(text);
} catch (Exception e) {
fd.setDefaultValue("0");
this.fd.setDefaultValue("0");
}
fd.setForeignTable(null);
fd.setLink(null);
this.fd.setForeignTable(null);
this.fd.setLink(null);
case TYPE_DECIMAL:
fd.setLength(null);
this.fd.setLength(null);
try {
text = text.replace(',', '.');
float i = Float.parseFloat(text);
fd.setDefaultValue(text);
this.fd.setDefaultValue(text);
} catch (Exception e) {
fd.setDefaultValue("0");
this.fd.setDefaultValue("0");
}
fd.setForeignTable(null);
fd.setLink(null);
this.fd.setForeignTable(null);
this.fd.setLink(null);
break;
 
}
extension.setChanged();
this.extension.setChanged();
 
}
}
 
protected void comboOptionModified() {
final int index = comboOption.getSelectedIndex();
final int index = this.comboOption.getSelectedIndex();
 
switch (this.comboType.getSelectedIndex()) {
 
case TYPE_BOOLEAN:
fd.setLength(null);
this.fd.setLength(null);
if (index == 0) {
fd.setDefaultValue("true");
this.fd.setDefaultValue("true");
} else {
fd.setDefaultValue("false");
this.fd.setDefaultValue("false");
}
fd.setForeignTable(null);
fd.setLink(null);
this.fd.setForeignTable(null);
this.fd.setLink(null);
break;
case TYPE_DATE:
case TYPE_TIME:
case TYPE_DATE_TIME:
fd.setLength(null);
this.fd.setLength(null);
if (index == 0) {
fd.setDefaultValue(null);
this.fd.setDefaultValue(null);
} else {
fd.setDefaultValue("now");
this.fd.setDefaultValue("now");
}
fd.setForeignTable(null);
fd.setLink(null);
this.fd.setForeignTable(null);
this.fd.setLink(null);
break;
case TYPE_REF:
fd.setLength(null);
fd.setDefaultValue(null);
fd.setDefaultValue("now");
fd.setForeignTable(comboOption.getSelectedItem().toString());
fd.setLink(null);
this.fd.setLength(null);
this.fd.setDefaultValue(null);
this.fd.setForeignTable(this.comboOption.getSelectedItem().toString());
this.fd.setLink(null);
break;
 
}
extension.setChanged();
this.extension.setChanged();
 
}
 
private void updateFrom(FieldDescriptor fd) {
if (fd.getType().equals("string")) {
comboType.setSelectedIndex(TYPE_STRING);
labelOption.setText("Longueur max");
textOption.setVisible(true);
textOption.setText(fd.getLength());
comboOption.setVisible(false);
this.comboType.setSelectedIndex(TYPE_STRING);
this.labelOption.setText("Longueur max");
this.textOption.setVisible(true);
this.textOption.setText(fd.getLength());
this.comboOption.setVisible(false);
} else if (fd.getType().equals("integer")) {
comboType.setSelectedIndex(TYPE_INTEGER);
labelOption.setText("Valeur par défaut");
textOption.setVisible(true);
textOption.setText(fd.getDefaultValue());
comboOption.setVisible(false);
this.comboType.setSelectedIndex(TYPE_INTEGER);
this.labelOption.setText("Valeur par défaut");
this.textOption.setVisible(true);
this.textOption.setText(fd.getDefaultValue());
this.comboOption.setVisible(false);
} else if (fd.getType().equals("decimal")) {
comboType.setSelectedIndex(TYPE_DECIMAL);
labelOption.setText("Valeur par défaut");
textOption.setVisible(true);
textOption.setText(fd.getDefaultValue());
comboOption.setVisible(false);
this.comboType.setSelectedIndex(TYPE_DECIMAL);
this.labelOption.setText("Valeur par défaut");
this.textOption.setVisible(true);
this.textOption.setText(fd.getDefaultValue());
this.comboOption.setVisible(false);
} else if (fd.getType().equals("boolean")) {
comboType.setSelectedIndex(TYPE_BOOLEAN);
labelOption.setText("Valeur par défaut");
textOption.setVisible(false);
comboOption.setVisible(true);
comboOption.setModel(new DefaultComboBoxModel(vBoolean));
this.comboType.setSelectedIndex(TYPE_BOOLEAN);
this.labelOption.setText("Valeur par défaut");
this.textOption.setVisible(false);
this.comboOption.setVisible(true);
this.comboOption.setModel(new DefaultComboBoxModel(vBoolean));
if (fd.getDefaultValue().equals("true")) {
comboOption.setSelectedIndex(0);
this.comboOption.setSelectedIndex(0);
} else {
comboOption.setSelectedIndex(1);
this.comboOption.setSelectedIndex(1);
}
 
} else if (fd.getType().equals("date")) {
comboType.setSelectedIndex(TYPE_DATE);
labelOption.setText("Valeur par défaut");
textOption.setVisible(false);
comboOption.setVisible(true);
comboOption.setModel(new DefaultComboBoxModel(vDate));
this.comboType.setSelectedIndex(TYPE_DATE);
this.labelOption.setText("Valeur par défaut");
this.textOption.setVisible(false);
this.comboOption.setVisible(true);
this.comboOption.setModel(new DefaultComboBoxModel(vDate));
if (fd.getDefaultValue() == null || !fd.getDefaultValue().equals("now")) {
comboOption.setSelectedIndex(0);
this.comboOption.setSelectedIndex(0);
} else {
comboOption.setSelectedIndex(1);
this.comboOption.setSelectedIndex(1);
}
} else if (fd.getType().equals("time")) {
comboType.setSelectedIndex(TYPE_TIME);
labelOption.setText("Valeur par défaut");
textOption.setVisible(false);
comboOption.setVisible(true);
comboOption.setModel(new DefaultComboBoxModel(vTime));
this.comboType.setSelectedIndex(TYPE_TIME);
this.labelOption.setText("Valeur par défaut");
this.textOption.setVisible(false);
this.comboOption.setVisible(true);
this.comboOption.setModel(new DefaultComboBoxModel(vTime));
if (fd.getDefaultValue() == null || !fd.getDefaultValue().equals("now")) {
comboOption.setSelectedIndex(0);
} else {
279,8 → 284,27
labelOption.setText("Table");
textOption.setVisible(false);
comboOption.setVisible(true);
comboOption.setModel(new DefaultComboBoxModel(getTables()));
final Vector<String> tables = new Vector<String>();
tables.addAll(Arrays.asList(getTables()));
String tableName = fd.getForeignTable();
if (!tables.contains(tableName)) {
tables.add(tableName);
}
comboOption.setModel(new DefaultComboBoxModel<String>(tables));
comboOption.setRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
if (value.toString().trim().isEmpty()) {
value = "!! non renseignée !!";
}
DefaultListCellRenderer r = (DefaultListCellRenderer) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (!tables.contains(value)) {
r.setForeground(Color.RED);
}
return r;
}
 
});
comboOption.setSelectedItem(tableName);
} else {
throw new IllegalArgumentException("Unknow type " + fd.getType());
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/table/TableModifyLeftPanel.java
53,24 → 53,24
 
private JComponent createModifiedTableList(final Extension extension) {
final ModifiedTableListModel dataModel = new ModifiedTableListModel(extension);
listTableModified = new JList(dataModel);
listTableModified.addListSelectionListener(new ListSelectionListener() {
this.listTableModified = new JList(dataModel);
this.listTableModified.addListSelectionListener(new ListSelectionListener() {
 
@Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
final TableDescritor tableDesc = (TableDescritor) listTableModified.getSelectedValue();
final TableDescritor tableDesc = (TableDescritor) TableModifyLeftPanel.this.listTableModified.getSelectedValue();
if (tableDesc != null) {
System.out.println("TableModifyLeftPanel.createModifiedTableList.valueChanged():" + tableDesc);
final TableModifyPanel p = new TableModifyPanel(extension.getSQLTable(tableDesc), tableDesc, extension, TableModifyLeftPanel.this);
tableModifyMainPanel.setRightPanel(p);
listTableAll.clearSelection();
TableModifyLeftPanel.this.tableModifyMainPanel.setRightPanel(p);
TableModifyLeftPanel.this.listTableAll.clearSelection();
}
}
 
}
});
final JScrollPane comp2 = new JScrollPane(listTableModified);
final JScrollPane comp2 = new JScrollPane(this.listTableModified);
comp2.setMinimumSize(new Dimension(250, 150));
comp2.setPreferredSize(new Dimension(250, 150));
return comp2;
78,25 → 78,25
 
private JComponent createAllTableList(final Extension extension) {
final AllTableListModel dataModel = new AllTableListModel(extension);
listTableAll = new JList(dataModel);
listTableAll.addListSelectionListener(new ListSelectionListener() {
this.listTableAll = new JList(dataModel);
this.listTableAll.addListSelectionListener(new ListSelectionListener() {
 
@Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
final SQLTable table = (SQLTable) listTableAll.getSelectedValue();
final SQLTable table = (SQLTable) TableModifyLeftPanel.this.listTableAll.getSelectedValue();
if (table != null) {
System.out.println("TableModifyLeftPanel.createAllTableList.valueChanged():" + table);
final TableModifyPanel p = new TableModifyPanel(table, extension.getOrCreateTableDescritor(table.getName()), extension, TableModifyLeftPanel.this);
tableModifyMainPanel.setRightPanel(p);
listTableModified.clearSelection();
TableModifyLeftPanel.this.tableModifyMainPanel.setRightPanel(p);
TableModifyLeftPanel.this.listTableModified.clearSelection();
}
}
 
}
});
listTableAll.setCellRenderer(new SQLTableListCellRenderer());
final JScrollPane comp2 = new JScrollPane(listTableAll);
this.listTableAll.setCellRenderer(new SQLTableListCellRenderer());
final JScrollPane comp2 = new JScrollPane(this.listTableAll);
comp2.setMinimumSize(new Dimension(150, 150));
comp2.setPreferredSize(new Dimension(150, 150));
return comp2;
105,11 → 105,11
public void selectTable(String tableName) {
System.out.println("TableModifyLeftPanel.selectTable():" + tableName);
if (tableName != null) {
TableDescritor tableDesc = extension.getOrCreateTableDescritor(tableName);
final TableModifyPanel p = new TableModifyPanel(extension.getSQLTable(tableDesc), tableDesc, extension, TableModifyLeftPanel.this);
tableModifyMainPanel.setRightPanel(p);
listTableAll.clearSelection();
listTableModified.clearSelection();
TableDescritor tableDesc = this.extension.getOrCreateTableDescritor(tableName);
final TableModifyPanel p = new TableModifyPanel(this.extension.getSQLTable(tableDesc), tableDesc, this.extension, TableModifyLeftPanel.this);
this.tableModifyMainPanel.setRightPanel(p);
this.listTableAll.clearSelection();
this.listTableModified.clearSelection();
}
}
 
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/table/TableCreatePanel.java
70,7 → 70,7
 
c.weightx = 1;
c.gridx = 0;
final FieldDescriptorEditor editor = new FieldDescriptorEditor(extension, field);
final FieldDescriptorEditor editor = new FieldDescriptorEditor(this.extension, field);
p.add(editor, c);
 
c.gridx++;
86,7 → 86,7
p.remove(editor);
p.remove(close);
p.revalidate();
extension.setChanged();
TableCreatePanel.this.extension.setChanged();
}
});
c.gridy++;
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/table/TableModifyInfoPanel.java
176,7 → 176,7
private void addField(final TableDescritor desc, final JPanel p, GridBagConstraints c, final FieldDescriptor field) {
c.weightx = 1;
c.gridx = 0;
final FieldDescriptorEditor editor = new FieldDescriptorEditor(extension, field);
final FieldDescriptorEditor editor = new FieldDescriptorEditor(this.extension, field);
p.add(editor, c);
 
c.gridx++;
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/table/TableCreateMainPanel.java
12,11 → 12,11
}
 
public void select(TableDescritor tableDescriptor) {
((TableListPanel) leftComponent).selectItem(tableDescriptor);
((TableListPanel) this.leftComponent).selectItem(tableDescriptor);
}
 
@Override
public JComponent createLeftComponent() {
return new TableListPanel(extension, this);
return new TableListPanel(this.extension, this);
}
}
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/table/TableListPanel.java
23,7 → 23,7
 
@Override
public void addNewItem() {
((CreateTableListModel) dataModel).addNewTable();
((CreateTableListModel) this.dataModel).addNewTable();
}
 
@Override
30,7 → 30,7
public void renameItem(Object item) {
final TableDescritor e = (TableDescritor) item;
final Window w = SwingUtilities.windowForComponent(this);
final String s = (String) JOptionPane.showInputDialog(w, "Nouveau nom", "Renommer la liste", JOptionPane.PLAIN_MESSAGE, null, null, e.getName());
final String s = (String) JOptionPane.showInputDialog(w, "Nouveau nom", "Renommer la table", JOptionPane.PLAIN_MESSAGE, null, null, e.getName());
if ((s != null) && (s.length() > 0)) {
e.setName(s);
}
38,8 → 38,8
 
@Override
public void removeItem(Object item) {
((CreateTableListModel) dataModel).removeElement(item);
extension.removeCreateTable((TableDescritor) item);
((CreateTableListModel) this.dataModel).removeElement(item);
this.extension.removeCreateTable((TableDescritor) item);
}
 
@Override
47,10 → 47,10
if (item != null) {
TableDescritor n = (TableDescritor) item;
System.out.println("TableListPanel..valueChanged():" + n);
final TableCreatePanel p = new TableCreatePanel(n, extension);
tableInfoPanel.setRightPanel(new JScrollPane(p));
final TableCreatePanel p = new TableCreatePanel(n, this.extension);
this.tableInfoPanel.setRightPanel(new JScrollPane(p));
} else {
tableInfoPanel.setRightPanel(new JPanel());
this.tableInfoPanel.setRightPanel(new JPanel());
}
}
}
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/table/ModifiedTableListModel.java
32,7 → 32,7
@Override
public void stateChanged(ChangeEvent e) {
this.clear();
addContent(extension);
addContent(this.extension);
this.fireContentsChanged(this, 0, this.getSize());
}
 
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/ExtensionInfoPanel.java
113,16 → 113,16
final JButton startButton = new JButton("Démarrer");
 
panel.add(startButton);
startButton.setEnabled(!extension.isStarted());
startButton.setEnabled(!this.extension.isStarted());
final JButton stopButton = new JButton("Arrêter");
panel.add(stopButton);
stopButton.setEnabled(extension.isStarted());
stopButton.setEnabled(this.extension.isStarted());
final JButton saveButton = new JButton("Enregister");
saveButton.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
extension.save();
ExtensionInfoPanel.this.extension.save();
 
}
});
137,10 → 137,10
 
@Override
public void actionPerformed(ActionEvent e) {
String xml = extension.toXML();
String xml = ExtensionInfoPanel.this.extension.toXML();
System.out.println(xml);
FileDialog fDialog = new FileDialog(new JFrame(), "Export", FileDialog.SAVE);
fDialog.setFile(extension.getName() + ".ocext");
fDialog.setFile(ExtensionInfoPanel.this.extension.getName() + ".ocext");
fDialog.setVisible(true);
String fileName = fDialog.getFile();
if (fileName != null) {
225,17 → 225,17
 
}
// Create extension from XML
extension.stop();
ExtensionInfoPanel.this.extension.stop();
if (!xml.isEmpty()) {
if (!extension.isEmpty()) {
if (!ExtensionInfoPanel.this.extension.isEmpty()) {
int result = JOptionPane.showConfirmDialog(ExtensionInfoPanel.this, "Attention l'extension actuelle sera écrasée.\nContinuer l'importation?");
if (result != JOptionPane.YES_OPTION) {
return;
}
}
extension.clearAll();
extension.importFromXML(xml);
extension.setChanged();
ExtensionInfoPanel.this.extension.clearAll();
ExtensionInfoPanel.this.extension.importFromXML(xml);
ExtensionInfoPanel.this.extension.setChanged();
}
 
}
251,9 → 251,23
public void run() {
final DBRoot root = ComptaPropsConfiguration.getInstanceCompta().getRootSociete();
try {
extension.start(root, false);
} catch (SQLException e1) {
e1.printStackTrace();
ExtensionInfoPanel.this.extension.start(root, false);
SwingUtilities.invokeLater(new Runnable() {
 
@Override
public void run() {
reload.setMode(ReloadPanel.MODE_EMPTY);
}
});
} catch (SQLException e) {
SwingUtilities.invokeLater(new Runnable() {
 
@Override
public void run() {
reload.setMode(ReloadPanel.MODE_BLINK);
}
});
ExceptionHandler.handle("Start error", e);
}
}
}).start();
267,7 → 281,26
new Thread(new Runnable() {
@Override
public void run() {
extension.stop();
try {
ExtensionInfoPanel.this.extension.stop();
SwingUtilities.invokeLater(new Runnable() {
 
@Override
public void run() {
reload.setMode(ReloadPanel.MODE_EMPTY);
}
});
} catch (Exception e) {
SwingUtilities.invokeLater(new Runnable() {
 
@Override
public void run() {
reload.setMode(ReloadPanel.MODE_BLINK);
}
});
ExceptionHandler.handle("Stop error", e);
}
 
}
}).start();
}
334,7 → 367,7
// --------- UI
panel.add(new JLabelBold("Interfaces de saisie"), c);
c.gridy++;
List<ComponentDescritor> createComponentList = extension.getCreateComponentList();
List<ComponentDescritor> createComponentList = this.extension.getCreateComponentList();
if (createComponentList.size() > 0) {
String components = "";
for (int i = 0; i < createComponentList.size(); i++) {
363,7 → 396,7
// --------- LIST
panel.add(new JLabelBold("Listes"), c);
c.gridy++;
List<ListDescriptor> createListList = extension.getCreateListList();
List<ListDescriptor> createListList = this.extension.getCreateListList();
if (createListList.size() > 0) {
String components = "";
for (int i = 0; i < createListList.size(); i++) {
391,9 → 424,9
// --------- MENUS
panel.add(new JLabelBold("Menus et actions"), c);
c.gridy++;
final int actionCount = extension.getActionDescriptors().size();
final int menuCount = extension.getCreateMenuList().size();
final int menuCount2 = extension.getRemoveMenuList().size();
final int actionCount = this.extension.getActionDescriptors().size();
final int menuCount = this.extension.getCreateMenuList().size();
final int menuCount2 = this.extension.getRemoveMenuList().size();
if (actionCount > 0) {
if (actionCount > 1)
panel.add(new JLabel(actionCount + " actions"), c);
427,9 → 460,9
panel.add(new JLabelBold("Traductions et renommage de labels"), c);
c.gridy++;
 
int actionTranslationCount = extension.getActionTranslations().size();
int menuTranslationCount = extension.getMenuTranslations().size();
int fieldTranslationCount = extension.getFieldTranslations().size();
int actionTranslationCount = this.extension.getActionTranslations().size();
int menuTranslationCount = this.extension.getMenuTranslations().size();
int fieldTranslationCount = this.extension.getFieldTranslations().size();
if (fieldTranslationCount > 0) {
if (fieldTranslationCount > 1)
panel.add(new JLabel(fieldTranslationCount + " traductions de champs"), c);
504,32 → 537,32
}
 
private void openTableEditor() {
final TableMainPanel contentPane = new TableMainPanel(extension);
openEditor(frameTableEditor, contentPane, "Tables dans la base de données");
final TableMainPanel contentPane = new TableMainPanel(this.extension);
openEditor(this.frameTableEditor, contentPane, "Tables dans la base de données");
 
}
 
private void openListEditor() {
final ListCreateMainPanel contentPane = new ListCreateMainPanel(extension);
openEditor(frameListEditor, contentPane, "Listes personnalisées");
final ListCreateMainPanel contentPane = new ListCreateMainPanel(this.extension);
openEditor(this.frameListEditor, contentPane, "Listes personnalisées");
 
}
 
protected void openComponentEditor() {
final ComponentCreateMainPanel contentPane = new ComponentCreateMainPanel(extension);
openEditor(frameListEditor, contentPane, "Interfaces personnalisées");
final ComponentCreateMainPanel contentPane = new ComponentCreateMainPanel(this.extension);
openEditor(this.frameListEditor, contentPane, "Interfaces personnalisées");
 
}
 
protected void openMenuEditor() {
final MenuMainPanel contentPane = new MenuMainPanel(extension);
openEditor(frameMenuEditor, contentPane, "Menus et actions");
final MenuMainPanel contentPane = new MenuMainPanel(this.extension);
openEditor(this.frameMenuEditor, contentPane, "Menus et actions");
 
}
 
protected void openTranslationEditor() {
final TranslationMainPanel contentPane = new TranslationMainPanel(extension);
openEditor(frameTranslationEditor, contentPane, "Traductions");
final TranslationMainPanel contentPane = new TranslationMainPanel(this.extension);
openEditor(this.frameTranslationEditor, contentPane, "Traductions");
 
}
 
536,7 → 569,7
private void openEditor(JFrame frame, JPanel mainPanel, String title) {
if (frame == null) {
frame = new JFrame();
frame.setTitle(extension.getName() + " - " + title);
frame.setTitle(this.extension.getName() + " - " + title);
frame.setContentPane(mainPanel);
frame.setMinimumSize(new Dimension(796, 560));
frame.pack();
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/ClickableLabel.java
25,7 → 25,7
 
public void paint(Graphics g) {
super.paint(g);
if (mouseOver) {
if (this.mouseOver) {
Rectangle r = g.getClipBounds();
final int y1 = r.height - getFontMetrics(getFont()).getDescent() + 1;
g.drawLine(0, y1, getFontMetrics(getFont()).stringWidth(getText()), y1);
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/Extension.java
91,22 → 91,22
public class Extension {
 
// Descriptors of the extension
private List<ElementDescriptor> elementList = new ArrayList<ElementDescriptor>();
private List<TableDescritor> createTableList = new ArrayList<TableDescritor>();
private List<TableDescritor> modifyTableList = new ArrayList<TableDescritor>();
private List<ListDescriptor> createListList = new ArrayList<ListDescriptor>();
private List<TableTranslation> tableTranslations = new ArrayList<TableTranslation>();
private List<FieldTranslation> fieldTranslations = new ArrayList<FieldTranslation>();
private List<MenuTranslation> menuTranslations = new ArrayList<MenuTranslation>();
private List<ActionTranslation> actionTranslations = new ArrayList<ActionTranslation>();
private List<ComponentDescritor> createComponentList = new ArrayList<ComponentDescritor>();
private List<ComponentDescritor> modifyComponentList = new ArrayList<ComponentDescritor>();
private List<MenuDescriptor> createMenuList = new ArrayList<MenuDescriptor>();
private List<MenuDescriptor> removeMenuList = new ArrayList<MenuDescriptor>();
private List<ActionDescriptor> createActionList = new ArrayList<ActionDescriptor>();
private List<ElementDescriptor> elementList = new ArrayList<>();
private List<TableDescritor> createTableList = new ArrayList<>();
private List<TableDescritor> modifyTableList = new ArrayList<>();
private List<ListDescriptor> createListList = new ArrayList<>();
private List<TableTranslation> tableTranslations = new ArrayList<>();
private List<FieldTranslation> fieldTranslations = new ArrayList<>();
private List<MenuTranslation> menuTranslations = new ArrayList<>();
private List<ActionTranslation> actionTranslations = new ArrayList<>();
private List<ComponentDescritor> createComponentList = new ArrayList<>();
private List<ComponentDescritor> modifyComponentList = new ArrayList<>();
private List<MenuDescriptor> createMenuList = new ArrayList<>();
private List<MenuDescriptor> removeMenuList = new ArrayList<>();
private List<ActionDescriptor> createActionList = new ArrayList<>();
 
// Listeners
private List<ChangeListener> listeners = new ArrayList<ChangeListener>();
private List<ChangeListener> listeners = new ArrayList<>();
 
private String name;
private boolean notSaved;
119,24 → 119,24
}
 
public void clearAll() {
elementList.clear();
createTableList.clear();
modifyTableList.clear();
createListList.clear();
tableTranslations.clear();
fieldTranslations.clear();
menuTranslations.clear();
actionTranslations.clear();
createComponentList.clear();
modifyComponentList.clear();
createMenuList.clear();
removeMenuList.clear();
createActionList.clear();
listeners.clear();
this.elementList.clear();
this.createTableList.clear();
this.modifyTableList.clear();
this.createListList.clear();
this.tableTranslations.clear();
this.fieldTranslations.clear();
this.menuTranslations.clear();
this.actionTranslations.clear();
this.createComponentList.clear();
this.modifyComponentList.clear();
this.createMenuList.clear();
this.removeMenuList.clear();
this.createActionList.clear();
this.listeners.clear();
 
notSaved = true;
autoStart = false;
isStarted = false;
this.notSaved = true;
this.autoStart = false;
this.isStarted = false;
 
}
 
145,7 → 145,7
}
 
public boolean isAutoStart() {
return autoStart;
return this.autoStart;
}
 
public void start(DBRoot root, boolean inModuleStart) throws SQLException {
156,14 → 156,13
Log.get().severe("Extension " + this.getName() + " not started due to database error");
return;
}
// Register translations
// Create menus
final MenuAndActions copy = MenuManager.getInstance().copyMenuAndActions();
registerMenuActions(copy);
// Register translations before setting menu
registerTranslations(root);
// Create menus
if (!inModuleStart) {
final MenuAndActions copy = MenuManager.getInstance().copyMenuAndActions();
registerMenuActions(copy);
MenuManager.getInstance().setMenuAndActions(copy);
}
MenuManager.getInstance().setMenuAndActions(copy);
 
Log.get().info("Extension " + this.getName() + " started");
this.isStarted = true;
this.autoStart = true;
282,21 → 281,14
}
}, menuDescriptor.getId(), true);
}
} else if (menuDescriptor.getType().equals(MenuDescriptor.LIST)) {
// No action to register
} else if (menuDescriptor.getType().equals(MenuDescriptor.GROUP)) {
// TODO
} else {
Log.get().warning("unknown type " + menuDescriptor.getType());
}
}
 
// System.err.println("****" + MenuManager.getInstance().getActionForId("test1"));
//
// final MenuAndActions copy = MenuManager.getInstance().copyMenuAndActions();
// // create group
// final Group group = copy.getGroup();
initMenuGroup(menuAndActions.getGroup());
// MenuManager.getInstance().setMenuAndActions(copy);
// System.err.println("*******" + MenuManager.getInstance().getActionForId("test1"));
}
 
public SQLTableModelSourceOnline createSource(SQLElement element, ListSQLRequest req, ListDescriptor listDesc) {
305,7 → 297,7
for (ColumnDescriptor cDesc : listDesc.getColumns()) {
final String fieldspath = cDesc.getFieldsPaths();
final String[] paths = fieldspath.split(",");
final Set<FieldPath> fps = new LinkedHashSet<FieldPath>();
final Set<FieldPath> fps = new LinkedHashSet<>();
for (int i = 0; i < paths.length; i++) {
// LOCAL, id_batiment.id_site.nom
final SQLName name = SQLName.parse(paths[i].trim());
417,13 → 409,13
}
 
private boolean setupDatabase(DBRoot root) throws SQLException {
List<ChangeTable<?>> changesToApply = new ArrayList<ChangeTable<?>>();
List<SQLCreateTable> createToApply = new ArrayList<SQLCreateTable>();
List<ChangeTable<?>> changesToApply = new ArrayList<>();
List<SQLCreateTable> createToApply = new ArrayList<>();
// Create fields and tables if needed
final List<TableDescritor> t = new ArrayList<TableDescritor>();
final List<TableDescritor> t = new ArrayList<>();
t.addAll(this.createTableList);
t.addAll(this.modifyTableList);
Set<String> tableNames = new HashSet<String>();
Set<String> tableNames = new HashSet<>();
for (TableDescritor tDesc : t) {
String tableName = tDesc.getName();
tableNames.add(tableName);
483,7 → 475,6
createTable.addDateAndTimeColumn(fieldName);
} else if (type.equals(FieldDescriptor.TYPE_REF)) {
// created later
mustAdd = false;
}
mustAdd = true;
} else {
520,14 → 511,20
final SQLField f = (table == null) ? null : table.getFieldRaw(fDesc.getName());
if (f == null && fDesc.getType().equals(FieldDescriptor.TYPE_REF)) {
final String fTableName = fDesc.getForeignTable();
final SQLTable fTable = root.getTable(fTableName);
if (fTable != null) {
final AlterTable mTable = new AlterTable(table);
mTable.addForeignColumn(fDesc.getName(), fTable);
changesToApply.add(mTable);
if (fTableName == null || fTableName.isEmpty()) {
JOptionPane.showMessageDialog(new JFrame(),
"L'extension ne peut pas s'installer car le champs référence " + fDesc.getName() + " de la table " + tDesc.getName() + " ne définit pas de table étrangère");
return false;
} else {
JOptionPane.showMessageDialog(new JFrame(), "L'extension ne peut pas s'installer car la table " + fTableName + " n'existe pas.");
return false;
final SQLTable fTable = root.getTable(fTableName);
if (fTable != null) {
final AlterTable mTable = new AlterTable(table);
mTable.addForeignColumn(fDesc.getName(), fTable);
changesToApply.add(mTable);
} else {
JOptionPane.showMessageDialog(new JFrame(), "L'extension ne peut pas s'installer car la table " + fTableName + " n'existe pas.");
return false;
}
}
}
}
558,7 → 555,7
}
 
public String getName() {
return name;
return this.name;
}
 
@SuppressWarnings("unchecked")
593,7 → 590,7
FieldDescriptor f = createFieldDescriptorFrom(name, field);
tDesc.add(f);
}
if (tDesc.getFields().size() > 0) {
if (!tDesc.getFields().isEmpty()) {
if (type.equals("create")) {
this.createTableList.add(tDesc);
} else if (type.equals("modify")) {
657,7 → 654,7
listDesc.setMainTable(mainTable);
final List<Element> columns = eList.getChildren("column");
for (Element field : columns) {
ColumnDescriptor f = createColumnDescriptorFrom(mainTable, field);
ColumnDescriptor f = createColumnDescriptorFrom(field);
listDesc.add(f);
}
if (listDesc.getColumnCount() > 0) {
756,7 → 753,7
e.printStackTrace();
}
}
notSaved = false;
this.notSaved = false;
 
fireChanged();
}
824,20 → 821,20
rootElement.addContent(eTable);
}
// Translations
final HashSet<String> locales = new HashSet<String>();
for (Translation tr : tableTranslations) {
final HashSet<String> locales = new HashSet<>();
for (Translation tr : this.tableTranslations) {
locales.add(tr.getLocale());
}
for (Translation tr : fieldTranslations) {
for (Translation tr : this.fieldTranslations) {
locales.add(tr.getLocale());
}
for (Translation tr : menuTranslations) {
for (Translation tr : this.menuTranslations) {
locales.add(tr.getLocale());
}
for (Translation tr : actionTranslations) {
for (Translation tr : this.actionTranslations) {
locales.add(tr.getLocale());
}
final List<String> lLocales = new ArrayList<String>(locales);
final List<String> lLocales = new ArrayList<>(locales);
Collections.sort(lLocales);
for (String locale : lLocales) {
final Element eTranslation = new Element("translation");
844,7 → 841,7
eTranslation.setAttribute("locale", locale);
rootElement.addContent(eTranslation);
// Tables
for (TableTranslation tTranslation : tableTranslations) {
for (TableTranslation tTranslation : this.tableTranslations) {
if (tTranslation.getLocale().equals(locale)) {
final Element eTable = new Element("element");
eTable.setAttribute("refid", tTranslation.getTableName());
856,7 → 853,7
if (plural != null && !plural.isEmpty()) {
eTable.setAttribute("plural", plural);
}
for (FieldTranslation fTranslation : fieldTranslations) {
for (FieldTranslation fTranslation : this.fieldTranslations) {
// Fields
if (fTranslation.getLocale().equals(locale) && fTranslation.getTableName().equals(tTranslation.getTableName())) {
final Element eField = new Element("item");
873,7 → 870,7
}
}
// Menus
for (MenuTranslation tMenu : menuTranslations) {
for (MenuTranslation tMenu : this.menuTranslations) {
if (tMenu.getLocale().equals(locale)) {
final Element eMenu = new Element("menu");
eMenu.setAttribute("refid", tMenu.getId());
883,7 → 880,7
}
 
// Actions
for (ActionTranslation tAction : actionTranslations) {
for (ActionTranslation tAction : this.actionTranslations) {
if (tAction.getLocale().equals(locale)) {
final Element eMenu = new Element("action");
eMenu.setAttribute("refid", tAction.getId());
1076,7 → 1073,7
return f;
}
 
private ColumnDescriptor createColumnDescriptorFrom(String table, Element field) {
private ColumnDescriptor createColumnDescriptorFrom(Element field) {
final ColumnDescriptor f = new ColumnDescriptor(field.getAttributeValue("id"));
f.setFieldsPaths(field.getAttributeValue("fields"));
f.setStyle(field.getAttributeValue("style"));
1084,7 → 1081,7
}
 
private void fireChanged() {
for (ChangeListener listener : listeners) {
for (ChangeListener listener : this.listeners) {
listener.stateChanged(new ChangeEvent(this));
}
 
1091,7 → 1088,7
}
 
public List<TableDescritor> getCreateTableList() {
return createTableList;
return this.createTableList;
}
 
public void addCreateTable(TableDescritor value) {
1105,11 → 1102,11
}
 
public List<TableDescritor> getModifyTableList() {
return modifyTableList;
return this.modifyTableList;
}
 
public List<ListDescriptor> getCreateListList() {
return createListList;
return this.createListList;
}
 
public ListDescriptor getCreateListFromId(String id) {
1154,8 → 1151,7
 
public SQLTable getSQLTable(TableDescritor tableDesc) {
try {
SQLTable t = ComptaPropsConfiguration.getInstanceCompta().getRootSociete().getTable(tableDesc.getName());
return t;
return ComptaPropsConfiguration.getInstanceCompta().getRootSociete().getTable(tableDesc.getName());
} catch (Exception e) {
return null;
}
1207,8 → 1203,8
}
 
public List<String> getAllKnownTableNames() {
final List<String> l = new ArrayList<String>();
final Set<String> s = new HashSet<String>();
final List<String> l = new ArrayList<>();
final Set<String> s = new HashSet<>();
for (SQLTable t : AllTableListModel.getAllDatabaseTables()) {
s.add(t.getName());
}
1240,7 → 1236,7
}
 
public List<String> getTranslatedFieldOfTable(String tableName) {
final List<String> l = new ArrayList<String>();
final List<String> l = new ArrayList<>();
for (FieldTranslation tr : this.fieldTranslations) {
if (tr.getTableName().equals(tableName)) {
l.add(tr.getFieldName());
1281,7 → 1277,7
}
 
public List<MenuDescriptor> getCreateMenuList() {
return createMenuList;
return this.createMenuList;
}
 
public void addCreateMenu(MenuDescriptor desc) {
1298,7 → 1294,7
}
 
public List<MenuDescriptor> getRemoveMenuList() {
return removeMenuList;
return this.removeMenuList;
}
 
public void addRemoveMenu(MenuDescriptor desc) {
1307,7 → 1303,7
}
 
public List<String> getAllKnownFieldName(String tableName) {
final Set<String> l = new HashSet<String>();
final Set<String> l = new HashSet<>();
// fields created in the extension
 
final List<TableDescritor> desc = getCreateTableList();
1332,11 → 1328,11
}
}
 
return new ArrayList<String>(l);
return new ArrayList<>(l);
}
 
public List<String> getAllKnownActionNames() {
ArrayList<String> s = new ArrayList<String>();
final Set<String> s = new HashSet<>();
Collection<SQLElement> elements = ComptaPropsConfiguration.getInstanceCompta().getDirectory().getElements();
for (SQLElement element : elements) {
Collection<IListeAction> actions = element.getRowActions();
1349,12 → 1345,13
}
}
}
Collections.sort(s);
return s;
final List<String> list = new ArrayList<>(s);
Collections.sort(list);
return list;
}
 
public List<String> getActionNames() {
ArrayList<String> s = new ArrayList<String>();
ArrayList<String> s = new ArrayList<>();
for (ActionDescriptor action : this.createActionList) {
s.add(action.getId());
}
1373,9 → 1370,20
return this.createActionList;
}
 
public void addCreateAction(ActionDescriptor obj) {
this.createActionList.add(obj);
setChanged();
}
 
public void removeCreateAction(ActionDescriptor obj) {
this.createActionList.remove(obj);
setChanged();
}
 
public boolean isEmpty() {
return createTableList.isEmpty() && modifyTableList.isEmpty() && createListList.isEmpty() && tableTranslations.isEmpty() && fieldTranslations.isEmpty() && menuTranslations.isEmpty()
&& actionTranslations.isEmpty() && createComponentList.isEmpty() && modifyComponentList.isEmpty() && createMenuList.isEmpty() && removeMenuList.isEmpty() && createActionList.isEmpty();
return this.createTableList.isEmpty() && this.modifyTableList.isEmpty() && this.createListList.isEmpty() && this.tableTranslations.isEmpty() && this.fieldTranslations.isEmpty()
&& this.menuTranslations.isEmpty() && this.actionTranslations.isEmpty() && this.createComponentList.isEmpty() && this.modifyComponentList.isEmpty() && this.createMenuList.isEmpty()
&& this.removeMenuList.isEmpty() && this.createActionList.isEmpty();
}
 
public String getTableNameForElementId(String id) {
1397,15 → 1405,24
}
 
public List<MenuTranslation> getMenuTranslations() {
return menuTranslations;
return this.menuTranslations;
}
 
public MenuTranslation getMenuTranslation(String menuId, String locale) {
for (MenuTranslation tr : this.menuTranslations) {
if (tr.getId().equals(menuId) && tr.getLocale().equals(locale)) {
return tr;
}
}
return null;
}
 
public List<ActionTranslation> getActionTranslations() {
return actionTranslations;
return this.actionTranslations;
}
 
public List<FieldTranslation> getFieldTranslations() {
return fieldTranslations;
return this.fieldTranslations;
}
 
public void removeChangeListener(ChangeListener listener) {
1429,10 → 1446,10
}
 
public void removeRemoveMenuForId(String id) {
for (int i = removeMenuList.size() - 1; i >= 0; i--) {
final MenuDescriptor m = removeMenuList.get(i);
for (int i = this.removeMenuList.size() - 1; i >= 0; i--) {
final MenuDescriptor m = this.removeMenuList.get(i);
if (m.getId().equals(id)) {
removeMenuList.remove(i);
this.removeMenuList.remove(i);
}
}
 
1439,10 → 1456,10
}
 
public void removeCreateMenuForId(String id) {
for (int i = createMenuList.size() - 1; i >= 0; i--) {
final MenuDescriptor m = createMenuList.get(i);
for (int i = this.createMenuList.size() - 1; i >= 0; i--) {
final MenuDescriptor m = this.createMenuList.get(i);
if (m.getId().equals(id)) {
createMenuList.remove(i);
this.createMenuList.remove(i);
}
}
 
1449,7 → 1466,7
}
 
public MenuDescriptor getRemoveMenuItemFromId(String itemId) {
for (MenuDescriptor m : removeMenuList) {
for (MenuDescriptor m : this.removeMenuList) {
if (m.getId().equals(itemId)) {
return m;
}
1459,9 → 1476,9
 
public void renameMenuItem(String previousId, String newId) {
if (!previousId.equals(newId)) {
final List<MenuDescriptor> descs = new ArrayList<MenuDescriptor>(createMenuList.size() + removeMenuList.size());
descs.addAll(createMenuList);
descs.addAll(removeMenuList);
final List<MenuDescriptor> descs = new ArrayList<>(this.createMenuList.size() + this.removeMenuList.size());
descs.addAll(this.createMenuList);
descs.addAll(this.removeMenuList);
for (MenuDescriptor m : descs) {
if (m.getId().equals(previousId)) {
m.setId(newId);
1473,7 → 1490,7
}
 
public void moveMenuItem(String itemId, String parentId) {
for (MenuDescriptor m : createMenuList) {
for (MenuDescriptor m : this.createMenuList) {
if (m.getId().equals(itemId)) {
m.setInsertInMenu(parentId);
}
1540,4 → 1557,5
fTranslation.setLabel(text);
 
}
 
}
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/translation/action/ActionTranslation.java
13,11 → 13,11
}
 
public String getId() {
return id;
return this.id;
}
 
public String getLabel() {
return label;
return this.label;
}
 
public void setLabel(String label) {
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/translation/action/ActionTranslationPanel.java
13,6 → 13,6
 
@Override
public JComponent createLeftComponent() {
return new ActionListPanel(extension, this);
return new ActionListPanel(this.extension, this);
}
}
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/translation/action/ActionListPanel.java
36,9 → 36,9
@Override
public void itemSelected(Object item) {
if (item != null) {
tableTranslationPanel.setRightPanel(new JScrollPane(new MenuTranslationItemEditor(new Item(item.toString()), extension)));
this.tableTranslationPanel.setRightPanel(new JScrollPane(new MenuTranslationItemEditor(new Item(item.toString()), this.extension)));
} else {
tableTranslationPanel.setRightPanel(new JPanel());
this.tableTranslationPanel.setRightPanel(new JPanel());
}
 
}
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/translation/LocaleSelector.java
36,10 → 36,10
}
 
Collections.sort(langs);
comboLang = new JComboBox(langs);
this.add(comboLang);
comboCountry = new JComboBox();
this.add(comboCountry);
this.comboLang = new JComboBox(langs);
this.add(this.comboLang);
this.comboCountry = new JComboBox();
this.add(this.comboCountry);
 
try {
this.setLocale(Locale.getDefault());
46,36 → 46,36
} catch (Exception e) {
System.err.println("LocaleSelector warning: unable to set current language");
}
comboLang.addActionListener(new ActionListener() {
this.comboLang.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
if (interactive) {
lang = comboLang.getSelectedItem().toString();
if (LocaleSelector.this.interactive) {
LocaleSelector.this.lang = LocaleSelector.this.comboLang.getSelectedItem().toString();
updateCountryFromLang();
country = comboCountry.getSelectedItem().toString();
LocaleSelector.this.country = LocaleSelector.this.comboCountry.getSelectedItem().toString();
fireActionPerformed();
}
}
 
});
comboCountry.addActionListener(new ActionListener() {
this.comboCountry.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
if (interactive) {
country = comboCountry.getSelectedItem().toString();
if (LocaleSelector.this.interactive) {
LocaleSelector.this.country = LocaleSelector.this.comboCountry.getSelectedItem().toString();
fireActionPerformed();
}
}
 
});
final int minWidth = comboLang.getPreferredSize().width * 2;
final int minHeight = comboLang.getPreferredSize().height;
comboLang.setMinimumSize(new Dimension(minWidth, minHeight));
comboLang.setPreferredSize(new Dimension(minWidth, minHeight));
comboCountry.setMinimumSize(new Dimension(minWidth, minHeight));
comboCountry.setPreferredSize(new Dimension(minWidth, minHeight));
final int minWidth = this.comboLang.getPreferredSize().width * 2;
final int minHeight = this.comboLang.getPreferredSize().height;
this.comboLang.setMinimumSize(new Dimension(minWidth, minHeight));
this.comboLang.setPreferredSize(new Dimension(minWidth, minHeight));
this.comboCountry.setMinimumSize(new Dimension(minWidth, minHeight));
this.comboCountry.setPreferredSize(new Dimension(minWidth, minHeight));
}
 
private void updateCountryFromLang() {
84,7 → 84,7
Locale[] l = Locale.getAvailableLocales();
for (int i = 0; i < l.length; i++) {
Locale lo = (Locale) l[i];
if (lo.getLanguage().equals(lang)) {
if (lo.getLanguage().equals(this.lang)) {
countries.add(lo.getCountry());
}
}
92,16 → 92,16
if (countries.isEmpty()) {
countries.add("");
}
comboCountry.setModel(new DefaultComboBoxModel(countries));
this.comboCountry.setModel(new DefaultComboBoxModel(countries));
}
 
public Locale getLocale() {
Locale[] l = Locale.getAvailableLocales();
if (country != null) {
if (this.country != null) {
 
for (int i = 0; i < l.length; i++) {
Locale lo = (Locale) l[i];
if (lo.getLanguage().equals(lang) && lo.getCountry().equals(country)) {
if (lo.getLanguage().equals(this.lang) && lo.getCountry().equals(this.country)) {
return lo;
}
}
108,7 → 108,7
}
for (int i = 0; i < l.length; i++) {
Locale lo = (Locale) l[i];
if (lo.getLanguage().equals(lang)) {
if (lo.getLanguage().equals(this.lang)) {
return lo;
}
}
126,9 → 126,9
this.lang = l.getLanguage();
this.country = l.getCountry();
System.err.println("LocaleSelector.setLocale() " + this.lang + " " + this.country);
this.comboLang.setSelectedItem(lang);
this.comboLang.setSelectedItem(this.lang);
updateCountryFromLang();
this.comboCountry.setSelectedItem(country);
this.comboCountry.setSelectedItem(this.country);
this.interactive = true;
}
 
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/translation/field/AllTableListPanel.java
32,9 → 32,9
@Override
public void itemSelected(Object item) {
if (item != null) {
tableTranslationPanel.setRightPanel(new JScrollPane(new TableTranslationEditorPanel(extension, (String) item)));
this.tableTranslationPanel.setRightPanel(new JScrollPane(new TableTranslationEditorPanel(this.extension, (String) item)));
} else {
tableTranslationPanel.setRightPanel(new JPanel());
this.tableTranslationPanel.setRightPanel(new JPanel());
}
 
}
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/translation/field/TableTranslationEditorPanel.java
64,13 → 64,13
c.fill = GridBagConstraints.BOTH;
final JSeparator sep = new JSeparator(JSeparator.VERTICAL);
this.add(sep, c);
hideableComponents.add(sep);
this.hideableComponents.add(sep);
c.gridheight = 1;
c.weightx = 1;
c.gridx++;
c.fill = GridBagConstraints.NONE;
final LocaleSelector comboLang2 = new LocaleSelector();
hideableComponents.add(comboLang2);
this.hideableComponents.add(comboLang2);
comboLang2.setLocale(Locale.ENGLISH);
this.add(comboLang2, c);
// Singular
81,10 → 81,10
this.add(new JLabel("Singulier", SwingConstants.RIGHT), c);
c.gridx++;
 
this.add(textSingular1, c);
this.add(this.textSingular1, c);
c.gridx += 2;
hideableComponents.add(textSingular2);
this.add(textSingular2, c);
this.hideableComponents.add(this.textSingular2);
this.add(this.textSingular2, c);
 
// Plural
c.gridx = 0;
92,10 → 92,10
c.weightx = 0;
this.add(new JLabel("Pluriel", SwingConstants.RIGHT), c);
c.gridx++;
this.add(textPlural1, c);
this.add(this.textPlural1, c);
c.gridx += 2;
hideableComponents.add(textPlural2);
this.add(textPlural2, c);
this.hideableComponents.add(this.textPlural2);
this.add(this.textPlural2, c);
 
// Fields
c.gridx = 0;
111,7 → 111,7
c.gridx = 2;
c.fill = GridBagConstraints.BOTH;
final JSeparator sep2 = new JSeparator(JSeparator.VERTICAL);
hideableComponents.add(sep2);
this.hideableComponents.add(sep2);
this.add(sep2, c);
 
c.fill = GridBagConstraints.HORIZONTAL;
122,14 → 122,14
this.add(new JLabel(fName, SwingConstants.RIGHT), c);
c.gridx++;
final JTextField t1 = new JTextField();
map1.put(fName, t1);
fieldsMap.put(t1, fName);
this.map1.put(fName, t1);
this.fieldsMap.put(t1, fName);
this.add(t1, c);
c.gridx += 2;
final JTextField t2 = new JTextField();
hideableComponents.add(t2);
fieldsMap.put(t2, fName);
map2.put(fName, t2);
this.hideableComponents.add(t2);
this.fieldsMap.put(t2, fName);
this.map2.put(fName, t2);
this.add(t2, c);
c.gridy++;
}
189,22 → 189,22
}
 
});
for (final JTextField textField : map1.values()) {
for (final JTextField textField : this.map1.values()) {
textField.getDocument().addDocumentListener(new SimpleDocumentListener() {
 
@Override
public void changedUpdate(DocumentEvent e, String text) {
extension.setFieldTranslation(tableName, fieldsMap.get(textField), comboLang1.getLocale(), text);
extension.setFieldTranslation(tableName, TableTranslationEditorPanel.this.fieldsMap.get(textField), comboLang1.getLocale(), text);
}
 
});
}
for (final JTextField textField : map2.values()) {
for (final JTextField textField : this.map2.values()) {
textField.getDocument().addDocumentListener(new SimpleDocumentListener() {
 
@Override
public void changedUpdate(DocumentEvent e, String text) {
extension.setFieldTranslation(tableName, fieldsMap.get(textField), comboLang2.getLocale(), text);
extension.setFieldTranslation(tableName, TableTranslationEditorPanel.this.fieldsMap.get(textField), comboLang2.getLocale(), text);
}
 
});
215,11 → 215,11
private void updateUIFrom(Extension extension, String tableName, Object l1, Object l2) {
if (l1 != null) {
final String lang = l1.toString();
updateUI(extension, tableName, lang, textSingular1, textPlural1, map1);
updateUI(extension, tableName, lang, this.textSingular1, this.textPlural1, this.map1);
}
if (l2 != null) {
final String lang = l2.toString();
updateUI(extension, tableName, lang, textSingular2, textPlural2, map2);
updateUI(extension, tableName, lang, this.textSingular2, this.textPlural2, this.map2);
}
 
}
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/translation/field/FieldTranslation.java
21,19 → 21,19
}
 
public String getTableName() {
return tableName;
return this.tableName;
}
 
public String getFieldName() {
return fieldName;
return this.fieldName;
}
 
public String getLabel() {
return label;
return this.label;
}
 
public String getDocumentation() {
return documentation;
return this.documentation;
}
 
public void setDocumentation(String documentation) {
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/translation/field/TableTranslation.java
14,7 → 14,7
}
 
public String getTableName() {
return tableName;
return this.tableName;
}
 
public void setSingular(String singular) {
22,7 → 22,7
}
 
public String getSingular() {
return singular;
return this.singular;
}
 
public void setPlural(String plural) {
30,6 → 30,6
}
 
public String getPlural() {
return plural;
return this.plural;
}
}
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/translation/field/TableTranslationPanel.java
10,20 → 10,20
 
public TableTranslationPanel(Extension extension) {
super(extension);
split.setDividerLocation(250);
this.split.setDividerLocation(250);
}
 
public void setRightPanel(JComponent p) {
super.setRightPanel(p);
split.setDividerLocation(250);
this.split.setDividerLocation(250);
}
 
@Override
public JComponent createLeftComponent() {
return new AllTableListPanel(extension, this);
return new AllTableListPanel(this.extension, this);
}
 
public void select(TableDescritor tableDescriptor) {
((AllTableListPanel) leftComponent).selectItem(tableDescriptor);
((AllTableListPanel) this.leftComponent).selectItem(tableDescriptor);
}
}
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/translation/menu/MenuTranslationItemEditor.java
2,6 → 2,8
 
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Locale;
 
import javax.swing.JLabel;
24,6 → 26,8
private JTextField textId;
private JTextField textTranslation1;
private JTextField textTranslation2;
final LocaleSelector comboLang1;
final LocaleSelector comboLang2;
 
public MenuTranslationItemEditor(final Item item, final Extension extension) {
this.extension = extension;
37,8 → 41,8
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;
c.gridwidth = 3;
textId = new JTextField();
this.add(textId, c);
this.textId = new JTextField();
this.add(this.textId, c);
 
// Language selector
c.gridx = 0;
50,7 → 54,7
final String[] isoLanguages = Locale.getISOLanguages();
System.out.println(isoLanguages.length);
 
final LocaleSelector comboLang1 = new LocaleSelector();
comboLang1 = new LocaleSelector();
 
c.weightx = 1;
c.gridx++;
67,7 → 71,7
c.weightx = 1;
c.gridx++;
c.fill = GridBagConstraints.NONE;
final LocaleSelector comboLang2 = new LocaleSelector();
comboLang2 = new LocaleSelector();
 
comboLang2.setLocale(Locale.ENGLISH);
this.add(comboLang2, c);
84,16 → 88,16
 
c.weightx = 1;
 
textTranslation1 = new JTextField(20);
this.textTranslation1 = new JTextField(20);
 
this.add(textTranslation1, c);
this.add(this.textTranslation1, c);
 
c.gridx += 2;
c.fill = GridBagConstraints.HORIZONTAL;
 
c.weightx = 1;
textTranslation2 = new JTextField(20);
this.add(textTranslation2, c);
this.textTranslation2 = new JTextField(20);
this.add(this.textTranslation2, c);
 
c.gridy++;
c.weighty = 1;
101,7 → 105,7
 
initUIFrom(item);
 
textTranslation1.getDocument().addDocumentListener(new DocumentListener() {
this.textTranslation1.getDocument().addDocumentListener(new DocumentListener() {
 
@Override
public void removeUpdate(DocumentEvent e) {
116,11 → 120,11
 
@Override
public void changedUpdate(DocumentEvent e) {
extension.setMenuTranslation(item.getId(), textTranslation1.getText(), comboLang1.getLocale());
extension.setMenuTranslation(item.getId(), MenuTranslationItemEditor.this.textTranslation1.getText(), comboLang1.getLocale());
extension.setChanged();
}
});
textTranslation2.getDocument().addDocumentListener(new DocumentListener() {
this.textTranslation2.getDocument().addDocumentListener(new DocumentListener() {
 
@Override
public void removeUpdate(DocumentEvent e) {
135,11 → 139,35
 
@Override
public void changedUpdate(DocumentEvent e) {
extension.setMenuTranslation(item.getId(), textTranslation2.getText(), comboLang2.getLocale());
extension.setMenuTranslation(item.getId(), MenuTranslationItemEditor.this.textTranslation2.getText(), comboLang2.getLocale());
extension.setChanged();
}
});
comboLang1.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
MenuTranslation t = extension.getMenuTranslation(textId.getText(), comboLang1.getLocale().toString());
if (t != null) {
textTranslation1.setText(t.getLabel());
} else {
textTranslation1.setText("");
}
}
});
comboLang2.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
MenuTranslation t = extension.getMenuTranslation(textId.getText(), comboLang2.getLocale().toString());
if (t != null) {
textTranslation2.setText(t.getLabel());
} else {
textTranslation2.setText("");
}
}
});
 
}
 
private void initUIFrom(Item item) {
146,10 → 174,21
 
final LayoutHints localHint = item.getLocalHint();
System.out.println("ItemEditor.initUIFrom:" + item + " " + localHint);
textId.setEnabled(false);
if (textId != null) {
textId.setText(item.getId());
this.textId.setEnabled(false);
if (this.textId != null) {
this.textId.setText(item.getId());
}
 
MenuTranslation t = extension.getMenuTranslation(textId.getText(), comboLang1.getLocale().toString());
if (t != null) {
textTranslation1.setText(t.getLabel());
} else {
textTranslation1.setText("");
}
t = extension.getMenuTranslation(textId.getText(), comboLang2.getLocale().toString());
if (t != null) {
textTranslation2.setText(t.getLabel());
} else {
textTranslation2.setText("");
}
}
}
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/translation/menu/MenuTranslation.java
13,7 → 13,7
}
 
public String getId() {
return id;
return this.id;
}
 
public void setLabel(String label) {
/trunk/Modules/Module Extension Builder/src/org/openconcerto/modules/extensionbuilder/translation/menu/MenuTranslationPanel.java
36,9 → 36,9
}
 
public void fillModel() {
newModel.fillFromDescriptor(extension);
tree.setModel(newModel);
tree.expandRow(0);
this.newModel.fillFromDescriptor(this.extension);
this.tree.setModel(this.newModel);
this.tree.expandRow(0);
}
 
@Override
54,8 → 54,8
c.insets = new Insets(2, 2, 2, 0);
 
panel.add(new JLabel("Menus"), c);
newModel = new MenuItemTreeModel();
tree = new JTree() {
this.newModel = new MenuItemTreeModel();
this.tree = new JTree() {
@Override
public String convertValueToText(Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
final Object userObject = ((DefaultMutableTreeNode) value).getUserObject();
69,10 → 69,10
return userObject.toString();
}
};
tree.setModel(newModel);
tree.setRootVisible(false);
tree.setShowsRootHandles(true);
tree.expandRow(0);
this.tree.setModel(this.newModel);
this.tree.setRootVisible(false);
this.tree.setShowsRootHandles(true);
this.tree.expandRow(0);
final DefaultTreeCellRenderer treeRenderer = new DefaultTreeCellRenderer() {
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
85,13 → 85,16
if (tr.getUserObject() instanceof Item) {
r.setText(((Item) tr.getUserObject()).getId());
}
if (sel) {
r.setForeground(Color.WHITE);
}
return r;
}
};
 
treeRenderer.setLeafIcon(null);
tree.setCellRenderer(treeRenderer);
final JScrollPane comp2 = new JScrollPane(tree);
this.tree.setCellRenderer(treeRenderer);
final JScrollPane comp2 = new JScrollPane(this.tree);
comp2.setMinimumSize(new Dimension(250, 150));
comp2.setPreferredSize(new Dimension(250, 150));
c.weighty = 1;
101,16 → 104,16
 
// init
 
tree.addMouseListener(new MouseAdapter() {
this.tree.addMouseListener(new MouseAdapter() {
 
@Override
public void mousePressed(MouseEvent e) {
final TreePath selectionPath = tree.getSelectionPath();
final TreePath selectionPath = MenuTranslationPanel.this.tree.getSelectionPath();
if (selectionPath == null) {
setRightPanel(new JPanel());
} else {
Item i = (Item) ((DefaultMutableTreeNode) selectionPath.getLastPathComponent()).getUserObject();
setRightPanel(new MenuTranslationItemEditor(i, extension));
setRightPanel(new MenuTranslationItemEditor(i, MenuTranslationPanel.this.extension));
}
}
});
/trunk/Modules/Module Subscription/src/org/openconcerto/modules/subscription/panel/BonCommandeAboPanel.java
8,10 → 8,10
import java.util.List;
 
import org.openconcerto.erp.core.common.element.NumerotationAutoSQLElement;
import org.openconcerto.erp.core.sales.order.element.CommandeClientSQLElement;
import org.openconcerto.erp.core.sales.order.report.CommandeClientXmlSheet;
import org.openconcerto.erp.model.MouseSheetXmlListeListener;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
26,17 → 26,18
}
 
private SQLTable tableNum = Configuration.getInstance().getRoot().findTable("NUMEROTATION_AUTO");
private SQLElement eltCmd = Configuration.getInstance().getDirectory().getElement("COMMANDE_CLIENT");
 
@Override
protected void injectRow(SQLRow row, SQLRowValues rowVals, Date dateNew, SQLRow rowAbonnement) {
// TODO Raccord de méthode auto-généré
super.injectRow(row, rowVals, dateNew, rowAbonnement);
rowVals.put("NUMERO", NumerotationAutoSQLElement.getNextNumero(CommandeClientSQLElement.class));
rowVals.put("NUMERO", NumerotationAutoSQLElement.getNextNumero(this.eltCmd.getClass()));
// incrémentation du numéro auto
final SQLRowValues rowValsNum = new SQLRowValues(this.tableNum);
int val = this.tableNum.getRow(2).getInt(NumerotationAutoSQLElement.getLabelNumberFor(CommandeClientSQLElement.class));
int val = this.tableNum.getRow(2).getInt(NumerotationAutoSQLElement.getLabelNumberFor(this.eltCmd.getClass()));
val++;
rowValsNum.put(NumerotationAutoSQLElement.getLabelNumberFor(CommandeClientSQLElement.class), new Integer(val));
rowValsNum.put(NumerotationAutoSQLElement.getLabelNumberFor(this.eltCmd.getClass()), new Integer(val));
try {
rowValsNum.update(2);
} catch (final SQLException e) {
/trunk/Modules/Module Subscription/src/org/openconcerto/modules/subscription/panel/DevisAboPanel.java
8,8 → 8,8
import java.util.Date;
 
import org.openconcerto.erp.core.common.element.NumerotationAutoSQLElement;
import org.openconcerto.erp.core.sales.quote.element.DevisSQLElement;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
21,18 → 21,19
}
 
private SQLTable tableNum = Configuration.getInstance().getRoot().findTable("NUMEROTATION_AUTO");
private SQLElement eltDev = Configuration.getInstance().getDirectory().getElement("DEVIS");
 
@Override
protected void injectRow(SQLRow row, SQLRowValues rowVals, Date dateNew, SQLRow rowAbonnement) {
super.injectRow(row, rowVals, dateNew, rowAbonnement);
String nextNumero = NumerotationAutoSQLElement.getNextNumero(DevisSQLElement.class);
String nextNumero = NumerotationAutoSQLElement.getNextNumero(this.eltDev.getClass());
rowVals.put("NUMERO", nextNumero);
 
// incrémentation du numéro auto
final SQLRowValues rowValsNum = new SQLRowValues(this.tableNum);
int val = this.tableNum.getRow(2).getInt(NumerotationAutoSQLElement.getLabelNumberFor(DevisSQLElement.class));
int val = this.tableNum.getRow(2).getInt(NumerotationAutoSQLElement.getLabelNumberFor(this.eltDev.getClass()));
val++;
rowValsNum.put(NumerotationAutoSQLElement.getLabelNumberFor(DevisSQLElement.class), new Integer(val));
rowValsNum.put(NumerotationAutoSQLElement.getLabelNumberFor(this.eltDev.getClass()), new Integer(val));
try {
rowValsNum.update(2);
} catch (final SQLException e) {
/trunk/Modules/Module Subscription/src/org/openconcerto/modules/subscription/panel/FacturesAboPanel.java
11,11 → 11,11
 
import org.openconcerto.erp.core.common.element.NumerotationAutoSQLElement;
import org.openconcerto.erp.core.finance.accounting.element.EcritureSQLElement;
import org.openconcerto.erp.core.sales.invoice.element.SaisieVenteFactureSQLElement;
import org.openconcerto.erp.core.sales.invoice.report.VenteFactureXmlSheet;
import org.openconcerto.erp.generationEcritures.GenerationMvtSaisieVenteFacture;
import org.openconcerto.erp.model.MouseSheetXmlListeListener;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.IResultSetHandler;
import org.openconcerto.sql.model.SQLDataSource;
import org.openconcerto.sql.model.SQLRow;
33,18 → 33,19
}
 
private final SQLTable tableNum = Configuration.getInstance().getRoot().findTable("NUMEROTATION_AUTO");
private SQLElement eltFact = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE");
 
@Override
protected void validItem(SQLRowAccessor sqlRowAccessor) {
// Affectation d'un numero
SQLRowValues rowVals = sqlRowAccessor.createEmptyUpdateRow();
String nextNumero = NumerotationAutoSQLElement.getNextNumero(SaisieVenteFactureSQLElement.class);
String nextNumero = NumerotationAutoSQLElement.getNextNumero(this.eltFact.getClass());
rowVals.put("DATE", new Date());
rowVals.put("NUMERO", nextNumero);
 
SQLRowValues rowValsNum = new SQLRowValues(tableNum);
 
String labelNumberFor = NumerotationAutoSQLElement.getLabelNumberFor(SaisieVenteFactureSQLElement.class);
String labelNumberFor = NumerotationAutoSQLElement.getLabelNumberFor(this.eltFact.getClass());
int val = tableNum.getRow(2).getInt(labelNumberFor);
val++;
rowValsNum.put(labelNumberFor, Integer.valueOf(val));
109,7 → 110,7
@Override
protected void injectRow(SQLRow row, SQLRowValues rowVals, Date dateNew, SQLRow rowAbonnement) {
super.injectRow(row, rowVals, dateNew, rowAbonnement);
rowVals.put("NUMERO", "ABO--" + NumerotationAutoSQLElement.getNextNumero(SaisieVenteFactureSQLElement.class));
rowVals.put("NUMERO", "ABO--" + NumerotationAutoSQLElement.getNextNumero(this.eltFact.getClass()));
rowVals.put("ID_ADRESSE", row.getObject("ID_ADRESSE"));
rowVals.put("ID_COMPTE_PCE_SERVICE", row.getObject("ID_COMPTE_PCE_SERVICE"));
rowVals.put("PORT_HT", row.getObject("PORT_HT"));
/trunk/Modules/Module Subscription/src/org/openconcerto/modules/subscription/panel/AboPanel.java
120,11 → 120,11
* @param type
*/
private void createUI(final SQLElement elt, final SQLElement itemsElement, final String type) {
final SQLTableModelSourceOnline tableCmd = elt.getTableSource(true);
final SwingWorker<SQLTableModelSourceOnline, Object> worker = new SwingWorker<SQLTableModelSourceOnline, Object>() {
 
@Override
protected SQLTableModelSourceOnline doInBackground() throws Exception {
final SQLTableModelSourceOnline tableCmd = elt.getTableSource(true);
Where wD = new Where(elt.getTable().getField("CREATION_AUTO_VALIDER"), "=", Boolean.FALSE);
wD = wD.and(new Where(elt.getTable().getField("ID_ABONNEMENT"), "IS NOT", (Object) null));
tableCmd.getReq().setWhere(wD);
/trunk/Modules/Module Subscription/src/org/openconcerto/modules/subscription/Module.java
40,7 → 40,6
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
import org.openconcerto.utils.i18n.TranslationManager;
 
public final class Module extends AbstractModule {
 
110,7 → 109,6
@Override
protected void setupElements(final SQLElementDirectory dir) {
super.setupElements(dir);
TranslationManager.getInstance().addTranslationStreamFromClass(this.getClass());
dir.addSQLElement(SubscriptionSQLElement.class);
NumerotationAutoSQLElement.addClass(SubscriptionSQLElement.class, "ABONNEMENT");
((SaisieVenteFactureSQLElement) dir.getElement("SAISIE_VENTE_FACTURE")).putSpecialAction("subscription.autocreate", new DoWithRow() {
/trunk/Modules/Module Google Docs/src/org/openconcerto/modules/google/docs/GoogleDocsPreferencePanel.java
101,8 → 101,10
ll.uploadFile(f, "OpenConcerto/Devis/2010", "Test Google Docs", true);
JOptionPane.showMessageDialog(GoogleDocsPreferencePanel.this, "Connexion réussie");
} catch (AuthenticationException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(GoogleDocsPreferencePanel.this, "Identifiant ou mot de passe invalide");
} catch (Throwable e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(GoogleDocsPreferencePanel.this, e1.getMessage());
}
}
/trunk/Modules/Module Customer Support/src/org/openconcerto/modules/customersupport/Module.java
1,6 → 1,5
package org.openconcerto.modules.customersupport;
 
import java.io.File;
import java.io.IOException;
import java.sql.Date;
import java.sql.SQLException;
9,7 → 8,6
import java.util.List;
import java.util.Set;
 
import org.openconcerto.erp.config.Gestion;
import org.openconcerto.erp.config.MainFrame;
import org.openconcerto.erp.modules.AbstractModule;
import org.openconcerto.erp.modules.ComponentsContext;
16,20 → 14,15
import org.openconcerto.erp.modules.DBContext;
import org.openconcerto.erp.modules.MenuContext;
import org.openconcerto.erp.modules.ModuleFactory;
import org.openconcerto.erp.modules.ModuleManager;
import org.openconcerto.erp.modules.ModulePackager;
import org.openconcerto.erp.modules.RuntimeModuleFactory;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.GlobalMapper;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.element.SQLElementDirectory;
import org.openconcerto.sql.model.FieldPath;
import org.openconcerto.sql.model.SQLRequestLog;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.model.graph.Path;
import org.openconcerto.sql.ui.ConnexionPanel;
import org.openconcerto.sql.utils.SQLCreateTable;
import org.openconcerto.sql.view.ListeAddPanel;
import org.openconcerto.sql.view.list.BaseSQLTableModelColumn;
/trunk/Modules/Module Customer Support/src/org/openconcerto/modules/customersupport/labels_fr.xml
1,7 → 1,7
<?xml version="1.0" encoding="UTF-8" ?>
<ROOT>
<element refid="customersupport.ticket" nameClass="masculine" name="ticket de support">
<FIELD name="STATUS" label="Status" />
<FIELD name="STATUS" label="Statut" />
<FIELD name="LABEL" label="Libellé" />
<FIELD name="ID_CLIENT" label="Client" />
<FIELD name="NUMBER" label="Numéro" />
10,7 → 10,7
<FIELD name="RATING" label="Priorité" />
<FIELD name="TYPE" label="Type" />
<FIELD name="REMIND_DATE" label="Prochain rappel le" />
<FIELD name="DATE" label="Date" />
<FIELD name="DATE" label="Date ticket" />
<FIELD name="CLOSED_AND_ARCHIVED" label="Archivé" />
</element>
<element refid="customersupport.ticket.history" nameClass="feminine" name="Intervention sur ticket">
17,6 → 17,6
<FIELD name="ID_CUSTOMER_SUPPORT_TICKET" label="Ticket" />
<FIELD name="ID_USER_COMMON" label="Utilisateur en charge" />
<FIELD name="INFORMATION" label="Détails de l'intervention" />
<FIELD name="DATE" label="Date" />
<FIELD name="DATE" label="Date inter." />
</element>
</ROOT>
/trunk/Modules/Module Operation/src/org/openconcerto/modules/operation/OperationExportPanel.java
74,13 → 74,13
public class OperationExportPanel extends JPanel {
 
@GuardedBy("EDT")
static private final DateFormat DF = new SimpleDateFormat("yyyyMMdd");
private static final DateFormat DF = new SimpleDateFormat("yyyyMMdd");
 
final JCheckBox lockedCheckBox = new JCheckBox("verrouillées uniquement");
final JButton bPrint = new JButton("Exporter");
 
public OperationExportPanel(final OperationCalendarManager manager, final List<SQLRowValues> rowsSite) {
lockedCheckBox.setSelected(true);
this.lockedCheckBox.setSelected(true);
//
this.setLayout(new GridBagLayout());
final GridBagConstraints c = new DefaultGridBagConstraints();
141,8 → 141,8
//
final JPanel p = new JPanel();
p.setLayout(new FlowLayout(FlowLayout.RIGHT));
p.add(lockedCheckBox);
p.add(bPrint);
p.add(this.lockedCheckBox);
p.add(this.bPrint);
c.gridwidth = 2;
c.gridx = 0;
c.gridy++;
151,7 → 151,7
this.add(p, c);
//
 
bPrint.addActionListener(new ActionListener() {
this.bPrint.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
160,9 → 160,9
}
final String statusVal = statusCombo.getValue();
final List<String> states = StringUtils.isEmpty(statusVal, true) ? null : Collections.singletonList(statusVal);
final List<JCalendarItem> items = manager.getItemIn(d1.getDate(), d2.getDate(), null, states);
final List<JCalendarItemDB> itemsToExport = new ArrayList<JCalendarItemDB>(items.size());
if (lockedCheckBox.isSelected()) {
final List<JCalendarItem> items = manager.getItemIn(d1.getDate(), d2.getDate(), manager.getAllUsers(), states);
final List<JCalendarItemDB> itemsToExport = new ArrayList<>(items.size());
if (OperationExportPanel.this.lockedCheckBox.isSelected()) {
for (JCalendarItem jCalendarItem : items) {
JCalendarItemDB i = (JCalendarItemDB) jCalendarItem;
if (i.getFlagsString().contains("locked")) {
176,12 → 176,12
}
}
if (rowsSite != null && !rowsSite.isEmpty()) {
final Set<String> allowedSites = new HashSet<String>();
final Set<String> allowedSites = new HashSet<>();
for (SQLRowValues r : rowsSite) {
String siteName = r.getString("NAME");
allowedSites.add(siteName);
}
final List<JCalendarItemDB> filtered = new ArrayList<JCalendarItemDB>(itemsToExport.size());
final List<JCalendarItemDB> filtered = new ArrayList<>(itemsToExport.size());
for (JCalendarItemDB i : itemsToExport) {
if (allowedSites.contains(i.getSiteName())) {
filtered.add(i);
218,9 → 218,9
});
}
 
static private final class Planner implements Comparable<Planner> {
private static final class Planner implements Comparable<Planner> {
 
static private final BigDecimal MS_PER_HOUR = BigDecimal.valueOf(1000 * 3600);
private static final BigDecimal MS_PER_HOUR = BigDecimal.valueOf(1000 * 3600);
 
private final String uid;
private final String xml;
256,7 → 256,7
 
final Element scheduleElem = doc.getRootElement().getChild("schedule");
this.startTime = new Date(Long.valueOf(scheduleElem.getAttributeValue("start")));
final long endTime = Long.valueOf(scheduleElem.getAttributeValue("end"));
final long endTime = Long.parseLong(scheduleElem.getAttributeValue("end"));
this.hours = DecimalUtils.round(BigDecimal.valueOf(endTime - this.startTime.getTime()).divide(MS_PER_HOUR, DecimalUtils.HIGH_PRECISION), 5);
} catch (Exception e) {
throw new IllegalStateException("couldn't get start for " + this.xml, e);
/trunk/Modules/Module Operation/src/org/openconcerto/modules/operation/OperationCalendarManager.java
62,6 → 62,10
this.userMngr = userMngr;
}
 
public UserManager getUserMngr() {
return userMngr;
}
 
public final SQLElementDirectory getDirectory() {
return this.dir;
}
389,4 → 393,15
}
return l.get(0);
}
 
/**
* Enabled or disabled users
*/
public List<User> getAllUsers() {
final List<User> result = new ArrayList<>();
for (User user : this.userMngr.getUsers().values()) {
result.add(user);
}
return result;
}
}
/trunk/Modules/Module Operation/src/org/openconcerto/modules/operation/JCalendarItemDB.java
25,7 → 25,13
assert r.isFrozen();
this.item = r;
this.group = dir.getElement(this.item.getTable()).getContainer(this.item);
if (this.group == null) {
throw new IllegalArgumentException("no group found for row " + r);
}
this.operationElem = dir.getElement(OperationSQLElement.class);
if (this.operationElem == null) {
throw new IllegalStateException("no element found " + OperationSQLElement.class);
}
this.operation = CollectionUtils.getSole(this.group.getReferentRows(this.operationElem.getTable()));
}
 
84,7 → 90,7
}
 
public String getStatus() {
return status;
return this.status;
}
 
public void setOperationType(String type) {
92,7 → 98,7
}
 
public String getType() {
return type;
return this.type;
}
 
public String getFlagsString() {
109,7 → 115,7
}
 
public String getPlannerXML() {
return plannerXML;
return this.plannerXML;
}
 
public void setPlannerXML(String string) {
117,7 → 123,7
}
 
public String getPlannerUID() {
return plannerUID;
return this.plannerUID;
}
 
public void setPlannerUID(String plannerUID) {
125,7 → 131,7
}
 
public String getSiteName() {
return siteName;
return this.siteName;
}
 
public void setSiteName(String siteName) {
133,7 → 139,7
}
 
public String getSiteComment() {
return siteComment;
return this.siteComment;
}
 
public void setSiteComment(String siteComment) {
145,7 → 151,7
}
 
public Number getSiteId() {
return siteId;
return this.siteId;
}
 
public int getId() {
/trunk/Modules/Module Operation/src/org/openconcerto/modules/operation/OperationCalendarItemPrinter.java
11,9 → 11,11
 
public class OperationCalendarItemPrinter extends CalendarItemPrinter {
public static final Font FONT_LINE = new Font("Arial", Font.PLAIN, 9);
private List<JCalendarItem> itemsToWork;
 
public OperationCalendarItemPrinter(String title, List<JCalendarItem> items, PageFormat pf) {
public OperationCalendarItemPrinter(String title, List<JCalendarItem> items, PageFormat pf, List<JCalendarItem> itemsToWork) {
super(title, items, pf);
this.itemsToWork = itemsToWork;
}
 
@Override
38,7 → 40,7
 
@Override
public String getTitle() {
final List<JCalendarItem> items = this.getItems();
final List<JCalendarItem> items = this.itemsToWork;
int totalMinutes = 0;
for (JCalendarItem jCalendarItem : items) {
long t2 = jCalendarItem.getDtEnd().getTimeInMillis();
/trunk/Modules/Module Operation/src/org/openconcerto/modules/operation/OperationHistoryPanel.java
72,6 → 72,7
public void propertyChange(PropertyChangeEvent evt) {
final List<SQLRowValues> selectedRows = list.getSelectedRows();
final IListPanel listePanel = listHistoriquePanel.getListePanel(0);
// Activation/Desactivation des boutons Mofifier/Supprimer
if (selectedRows != null && !selectedRows.isEmpty()) {
final Set<Long> idsCalendarItemGroup = new HashSet<>();
for (SQLRowValues sqlRowValues : selectedRows) {
142,24 → 143,25
cal.set(Calendar.YEAR, selectedYear + 1);
Date dEnd = cal.getTime();
 
final SQLTable groupT = comboRequest.getPrimaryTable().getTable("CALENDAR_ITEM_GROUP");
final SQLTable calItemT = comboRequest.getPrimaryTable().getTable("CALENDAR_ITEM");
final SQLTable itemGroupTable = comboRequest.getPrimaryTable().getTable("CALENDAR_ITEM_GROUP");
final SQLTable itemTable = comboRequest.getPrimaryTable().getTable("CALENDAR_ITEM");
final SQLTable operationTable = comboRequest.getPrimaryTable().getTable("OPERATION");
final List<?> dateGroupIDs;
{
final SQLSelect copy = new SQLSelect(input);
copy.clearSelect();
copy.addSelect(copy.getAlias(groupT.getKey()));
copy.setWhere(copy.getAlias(comboRequest.getPrimaryTable().getTable("OPERATION").getField("ID_SITE")), "=", panel.getSelectedRow().getID());
final List<?> allGroupIDs = calItemT.getDBSystemRoot().getDataSource().executeCol(copy.asString());
 
copy.addSelect(copy.getAlias(itemGroupTable.getKey()));
copy.setWhere(copy.getAlias(operationTable.getField("ID_SITE")), "=", panel.getSelectedRow().getID());
final List<?> allGroupIDs = itemTable.getDBSystemRoot().getDataSource().executeCol(copy.asString());
final SQLSelect selIDGroup = new SQLSelect();
selIDGroup.addSelect(calItemT.getField("ID_CALENDAR_ITEM_GROUP"));
final Where where = new Where(calItemT.getField("START"), dStart, true, dEnd, true);
selIDGroup.setWhere(where).andWhere(new Where(calItemT.getField("ID_CALENDAR_ITEM_GROUP"), allGroupIDs));
dateGroupIDs = calItemT.getDBSystemRoot().getDataSource().executeCol(selIDGroup.asString());
selIDGroup.addSelect(itemTable.getField("ID_CALENDAR_ITEM_GROUP"));
final Where where = new Where(itemTable.getField("START"), dStart, true, dEnd, true);
selIDGroup.setWhere(where).andWhere(new Where(itemTable.getField("ID_CALENDAR_ITEM_GROUP"), allGroupIDs));
dateGroupIDs = itemTable.getDBSystemRoot().getDataSource().executeCol(selIDGroup.asString());
}
 
input.setWhere(new Where(input.getAlias(groupT.getKey()), dateGroupIDs));
Where w = new Where(input.getAlias(itemGroupTable.getKey()), dateGroupIDs);
input.setWhere(w);
} catch (Throwable e) {
e.printStackTrace();
}
/trunk/Modules/Module Operation/src/org/openconcerto/modules/operation/CalendarPrintPanel.java
43,6 → 43,8
private static final double POINTS_PER_INCH = 72.0;
 
public CalendarPrintPanel(final OperationCalendarManager manager, final int week, final int year, final List<User> selectedUsers, final List<String> selectedStates) {
 
System.err.println("CalendarPrintPanel.CalendarPrintPanel()" + selectedUsers);
preview.setSelected(true);
//
this.setLayout(new GridBagLayout());
109,8 → 111,15
});
final PageFormat pf = new PageFormat();
pf.setPaper(new A4());
final CalendarItemPrinter printable = new OperationCalendarItemPrinter(user.getFullName(), itemInWeek, pf);
List<JCalendarItem> itemsToWork = new ArrayList<>();
for (JCalendarItem item : itemInWeek) {
if (!item.hasFlag(ModuleOperation.FREE_TIME_FLAG)) {
itemsToWork.add(item);
}
}
 
final CalendarItemPrinter printable = new OperationCalendarItemPrinter(user.getFullName(), itemInWeek, pf, itemsToWork);
 
p.add(printable);
}
}
/trunk/Modules/Module Operation/src/org/openconcerto/modules/operation/ModuleOperation.java
62,8 → 62,6
// SQLRequestLog.showFrame();
TemplateManager.getInstance().register(OPERATIONS_REPORT_TEMPLATE_ID);
TemplateManager.getInstance().register(OPERATIONS_REPORT_TEMPLATE2_ID);
// Translation loading
TranslationManager.getInstance().addTranslationStreamFromClass(this.getClass());
}
 
@Override
148,6 → 146,10
createTableOperation.addVarCharColumn("DESCRIPTION", 10000);
createTableOperation.addVarCharColumn("PLANNER_UID", 2048);
createTableOperation.addVarCharColumn("PLANNER_XML", 2048);
 
ctxt.executeSQL();
// SQLTable.setUndefID(ctxt.getRoot().getSchema(), TABLE_SITE, null);
// SQLTable.setUndefID(ctxt.getRoot().getSchema(), TABLE_OPERATION, null);
}
}
 
/trunk/Modules/Module Operation/src/org/openconcerto/modules/operation/OperationCalendarPanel.java
117,12 → 117,11
this.beginStateSaving(conf.getConfDir(), w);
}
 
public static Map<Integer, Long> getDurations(List<List<JCalendarItem>> list, final Flag requiredFlag) {
public static Map<Integer, Long> getDurations(List<List<JCalendarItem>> list, final Flag requiredFlag, final Flag excludedFlag) {
final Map<Integer, Long> res = new HashMap<>();
final Flag freeTimeFlag = ModuleOperation.FREE_TIME_FLAG;
for (List<JCalendarItem> items : list) {
for (JCalendarItem item : items) {
if (!item.hasFlag(freeTimeFlag) && (requiredFlag == null || item.hasFlag(requiredFlag)) && item.getCookie() instanceof SQLRowValues) {
if (!item.hasFlag(excludedFlag) && (requiredFlag == null || item.hasFlag(requiredFlag)) && item.getCookie() instanceof SQLRowValues) {
final SQLRowValues user = (SQLRowValues) item.getCookie();
final long toAddMinutes = (item.getDtEnd().getTimeInMillis() - item.getDtStart().getTimeInMillis()) / (60 * 1000);
final Integer key = user.getID();
/trunk/Modules/Module Operation/src/org/openconcerto/modules/operation/UserOperationListModel.java
140,7 → 140,7
return this.usersAndWeeklyMinutes;
}
}
final Map<User, Integer> uInfo = new LinkedHashMap<User, Integer>();
final Map<User, Integer> uInfo = new LinkedHashMap<>();
final SQLRowValues v = new SQLRowValues(this.salarieElem.getTable());
v.putNulls("NOM", "PRENOM");
v.putRowValues("ID_INFOS_SALARIE_PAYE").putNulls("DUREE_HEBDO");
152,10 → 152,14
for (int i = 0; i < size; i++) {
final User u = users.get(i);
final String name = u.getName().trim();
final String firstName = u.getFirstName();
final String firstName = u.getFirstName().trim();
Integer minutes = null;
for (SQLRowValues row : rows) {
if (row.getString("NOM").trim().equalsIgnoreCase(name) && row.getString("PRENOM").trim().equalsIgnoreCase(firstName)) {
// Matching Utilisateur <-> Salarié
// Nom et prénom identique
final String sName = row.getString("NOM").trim();
final String sFirstName = row.getString("PRENOM").trim();
if (sName.equalsIgnoreCase(name) && sFirstName.equalsIgnoreCase(firstName)) {
minutes = (int) row.getForeign("ID_INFOS_SALARIE_PAYE").getFloat("DUREE_HEBDO") * 60;
break;
}
169,8 → 173,8
}
 
private void setDurations(final List<List<JCalendarItem>> viewItems) {
final Map<Integer, Long> all = OperationCalendarPanel.getDurations(viewItems, null);
final Map<Integer, Long> locked = OperationCalendarPanel.getDurations(viewItems, Flag.getFlag("locked"));
final Map<Integer, Long> all = OperationCalendarPanel.getDurations(viewItems, null, ModuleOperation.FREE_TIME_FLAG);
final Map<Integer, Long> locked = OperationCalendarPanel.getDurations(viewItems, Flag.getFlag("locked"), ModuleOperation.FREE_TIME_FLAG);
synchronized (this) {
this.allDurations = Collections.unmodifiableMap(all);
this.lockedDurations = Collections.unmodifiableMap(locked);
217,10 → 221,10
// not a SALARIE
suffix = "";
} else {
// Durée verrouillée
final int d2 = getDuration(locked, u.getId());
// Durée planifiée
final int d = getDuration(all, u.getId());
// Durée verrouillée
final int d2 = getDuration(locked, u.getId());
suffix = " [" + formatDuration(d2) + " / " + formatDuration(d) + " / " + formatDuration(weeklyMinutes) + "]";
}
res.add(createItem(u, (u.getFullName() + suffix).trim()));
/trunk/Modules/Module Operation/src/org/openconcerto/modules/operation/UserColor.java
18,12 → 18,16
final int size = users.size();
for (int i = 0; i < size; i++) {
final User u = users.get(i);
map.put(u.getId(), Color.decode(COLORS[i % COLORS.length]));
if (u.getColor() == null) {
this.map.put(u.getId(), Color.decode(COLORS[i % COLORS.length]));
} else {
this.map.put(u.getId(), u.getColor());
}
}
}
 
public synchronized Color getColor(int id) {
return map.get(id);
return this.map.get(id);
}
 
public static final synchronized UserColor getInstance() {
/trunk/Modules/Module Badge/src/org/openconcerto/modules/badge/Module.java
31,7 → 31,7
import org.openconcerto.erp.core.common.element.AdresseSQLElement;
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.erp.core.common.ui.ListeViewPanel;
import org.openconcerto.erp.core.customerrelationship.customer.element.ContactSQLElement;
import org.openconcerto.erp.core.customerrelationship.customer.element.ComptaContactSQLElement;
import org.openconcerto.erp.core.customerrelationship.customer.element.CustomerSQLElement;
import org.openconcerto.erp.modules.AbstractModule;
import org.openconcerto.erp.modules.ComponentsContext;
166,6 → 166,7
 
createTable.addForeignColumn("ID_ADRESSE", addrElem.getTable());
createTable.addForeignColumn("ID_PLAGE_HORAIRE", new SQLName("PLAGE_HORAIRE"), SQLSyntax.ID_NAME, null);
ctxt.executeSQL();
}
// at least v1.0
 
240,7 → 241,7
vals.put("CODE", code);
newClient = vals.insert();
}
final SQLRowValues contactVals = new SQLRowValues(ctxt.getElementDirectory().getElement(ContactSQLElement.class).getTable());
final SQLRowValues contactVals = new SQLRowValues(ctxt.getElementDirectory().getElement(ComptaContactSQLElement.class).getTable());
contactVals.putForeignID("ID_CLIENT", newClient);
contactVals.load(adhR.asRow(), Arrays.asList("NOM", "DATE_NAISSANCE"));
contactVals.put("PRENOM", firstName);
/trunk/Modules/Module Lead/src/org/openconcerto/modules/customerrelationship/lead/visit/CustomerVisitSQLElement.java
28,6 → 28,10
final List<String> l = new ArrayList<String>();
l.add("DATE");
l.add("ID_CLIENT");
l.add("INFORMATION");
if (getTable().contains("ID_COMMERCIAL")) {
l.add("ID_COMMERCIAL");
}
l.add("NEXTCONTACT_DATE");
return l;
}
/trunk/Modules/Module Lead/src/org/openconcerto/modules/customerrelationship/lead/visit/LeadActionItemTable.java
New file
0,0 → 1,106
package org.openconcerto.modules.customerrelationship.lead.visit;
 
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.io.File;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Vector;
 
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ToolTipManager;
 
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLBackgroundTableCache;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.users.UserManager;
import org.openconcerto.sql.view.list.RowValuesTable;
import org.openconcerto.sql.view.list.RowValuesTableControlPanel;
import org.openconcerto.sql.view.list.RowValuesTableModel;
import org.openconcerto.sql.view.list.RowValuesTableRenderer;
import org.openconcerto.sql.view.list.SQLTableElement;
import org.openconcerto.ui.table.TimestampTableCellEditor;
 
public class LeadActionItemTable extends JPanel {
 
private RowValuesTable table;
final RowValuesTableControlPanel comp;
 
public LeadActionItemTable(SQLElement elt) {
this.setOpaque(false);
this.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = 1;
c.gridheight = 1;
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;
c.weighty = 0;
 
List<SQLTableElement> list = new Vector<SQLTableElement>();
 
SQLTableElement tableElementDateL = new SQLTableElement(elt.getTable().getField("DATE"), Timestamp.class, new TimestampTableCellEditor());
list.add(tableElementDateL);
 
SQLTableElement tableElementTps = new SQLTableElement(elt.getTable().getField("INFORMATION"));
list.add(tableElementTps);
 
if (elt.getTable().contains("ID_COMMERCIAL")) {
SQLTableElement tableElementCom = new SQLTableElement(elt.getTable().getField("ID_COMMERCIAL"));
list.add(tableElementCom);
}
 
SQLRowValues rowValsDefault = new SQLRowValues(elt.getTable());
rowValsDefault.put("DATE", new Date());
if (elt.getTable().contains("ID_COMMERCIAL")) {
final int idUser = UserManager.getInstance().getCurrentUser().getId();
final SQLElement eltComm = elt.getForeignElement("ID_COMMERCIAL");
SQLRow rowsComm = SQLBackgroundTableCache.getInstance().getCacheForTable(eltComm.getTable()).getFirstRowContains(idUser, eltComm.getTable().getField("ID_USER_COMMON"));
 
if (rowsComm != null) {
rowValsDefault.put("ID_COMMERCIAL", rowsComm.getID());
}
}
final RowValuesTableModel model = new RowValuesTableModel(elt, list, elt.getTable().getField("DATE"), false, rowValsDefault);
 
this.table = new RowValuesTable(model, new File(Configuration.getInstance().getConfDir(), "Table" + File.separator + "Table_LeadActionItemTable.xml"));
ToolTipManager.sharedInstance().unregisterComponent(this.table);
ToolTipManager.sharedInstance().unregisterComponent(this.table.getTableHeader());
this.comp = new RowValuesTableControlPanel(this.table);
this.add(this.comp, c);
 
c.gridy++;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.weighty = 1;
this.add(new JScrollPane(this.table), c);
this.table.setDefaultRenderer(Long.class, new RowValuesTableRenderer());
}
 
public void updateField(String field, int id) {
this.table.updateField(field, id);
}
 
public void insertFrom(String field, SQLRowValues row) {
this.table.insertFrom(field, row);
}
 
public void insertFrom(String field, int id) {
this.table.insertFrom(field, id);
}
 
public RowValuesTableModel getModel() {
return this.table.getRowValuesTableModel();
}
 
public void setEditable(boolean b) {
this.comp.setEditable(b);
this.table.setEditable(b);
}
 
}
/trunk/Modules/Module Lead/src/org/openconcerto/modules/customerrelationship/lead/visit/LeadVisitSQLElement.java
28,6 → 28,11
final List<String> l = new ArrayList<String>();
l.add("DATE");
l.add("ID_LEAD");
l.add("INFORMATION");
if (getTable().contains("ID_COMMERCIAL")) {
l.add("ID_COMMERCIAL");
}
 
l.add("NEXTCONTACT_DATE");
return l;
}
/trunk/Modules/Module Lead/src/org/openconcerto/modules/customerrelationship/lead/importer/LeadImporter.java
19,10 → 19,15
import org.openconcerto.openoffice.spreadsheet.Sheet;
import org.openconcerto.openoffice.spreadsheet.SpreadSheet;
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowListRSH;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLRowValuesCluster;
import org.openconcerto.sql.model.SQLRowValuesCluster.StoreMode;
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
import org.openconcerto.sql.model.SQLRowValuesCluster.StoreMode;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.utils.cc.IdentityHashSet;
import org.openconcerto.utils.text.CSVReader;
import org.openconcerto.utils.text.CharsetHelper;
76,6 → 81,82
public abstract T convert(String[] line);
}
 
public Map<Object, LeadCSV> exportLeads(SQLTable tableLead, File dir2save, File sheetFile) throws Exception {
List<String[]> adresse = new ArrayList<String[]>();
List<String[]> leadList = new ArrayList<String[]>();
 
Map<Object, LeadCSV> leadMap = new HashMap<Object, LeadCSV>();
 
SQLSelect sel = new SQLSelect();
sel.addSelectStar(tableLead);
List<SQLRow> leads = SQLRowListRSH.execute(sel);
int i = 1;
for (SQLRow lead : leads) {
 
int idAdr = adresse.size();
AdresseCSV adr = createAdresse(i, lead.getForeign("ID_ADRESSE"));
adresse.add(adr.toCSVLine());
LeadCSV leadCsv = createLeadFromRow(i, lead, Integer.valueOf(adr.getId().toString()));
leadList.add(leadCsv.toCSVLine());
leadMap.put(leadCsv.getId(), leadCsv);
i++;
}
 
DataImporter importer = new DataImporter(tableLead);
final File csvFile = new File(dir2save, "Lead.csv");
csvFile.createNewFile();
importer.exportModelToCSV(csvFile, leadList);
DataImporter importerAdr = new DataImporter(tableLead.getForeignTable("ID_ADRESSE"));
final File csvFile2 = new File(dir2save, "Address.csv");
csvFile2.createNewFile();
importerAdr.exportModelToCSV(csvFile2, adresse);
 
return leadMap;
}
 
public AdresseCSV createAdresse(int i, SQLRow rowAdr) {
 
String street = rowAdr.getString("RUE");
final String ville = rowAdr.getString("VILLE");
final String cp = rowAdr.getString("CODE_POSTAL");
 
AdresseCSV adrLine = new AdresseCSV(i, street, ville, cp);
 
return adrLine;
}
 
public LeadCSV createLeadFromRow(int i, SQLRowAccessor row, int idAdr) {
 
LeadCSV leadLine = new LeadCSV(i, row.getString("COMPANY"), "");
 
leadLine.setIdAdr(idAdr);
 
leadLine.setPhone(row.getString("PHONE"));
leadLine.setMail(row.getString("EMAIL"));
leadLine.setCell(row.getString("MOBILE"));
leadLine.setFax(row.getString("FAX"));
leadLine.setContact(row.getString("NAME"));
leadLine.setLocalisation(row.getString("LOCALISATION"));
leadLine.setSecteur(row.getString("INDUSTRY"));
leadLine.setEffectif(String.valueOf(row.getInt("EMPLOYEES")));
leadLine.setOrigine(row.getString("SOURCE"));
 
leadLine.setSiret(row.getString("SIRET"));
leadLine.setApe(row.getString("APE"));
 
leadLine.setNom(row.getString("NAME"));
leadLine.setPrenom(row.getString("FIRSTNAME"));
leadLine.setDesc(row.getString("INFORMATION"));
// rowVals.put("REVENUE", (getBudget().trim().length()==0?0:Integer);
leadLine.setDispo(row.getString("DISPO"));
leadLine.setTypeT(row.getString("INDUSTRY"));
leadLine.setStatut(row.getString("STATUS"));
leadLine.setInfos(row.getString("INFOS"));
 
return leadLine;
 
}
 
public LeadCSV createLead(int i, Sheet sheet, int idAdr, int id) {
final Cell<SpreadSheet> cell0 = sheet.getImmutableCellAt(0, i);
final String societeName = cell0.getValue().toString().trim();
/trunk/Modules/Module Lead/src/org/openconcerto/modules/customerrelationship/lead/LeadGroup.java
1,6 → 1,5
package org.openconcerto.modules.customerrelationship.lead;
 
import org.openconcerto.sql.users.UserManager;
import org.openconcerto.sql.users.rights.UserRights;
import org.openconcerto.sql.users.rights.UserRightsManager;
import org.openconcerto.ui.group.Group;
11,52 → 10,59
public LeadGroup() {
super("customerrelationship.lead.default");
final Group g = new Group("customerrelationship.lead.identifier");
g.addItem("NUMBER");
g.addItem("DATE");
g.addItem("NUMBER", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
g.addItem("DATE", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
g.addItem("COMPANY", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
this.add(g);
 
final Group gContact = new Group("customerrelationship.lead.person", LayoutHints.DEFAULT_SEPARATED_GROUP_HINTS);
gContact.addItem("NAME");
gContact.addItem("FIRSTNAME");
gContact.addItem("ID_TITRE_PERSONNEL");
gContact.addItem("ID_TITRE_PERSONNEL", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
gContact.addItem("NAME", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
gContact.addItem("FIRSTNAME", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
this.add(gContact);
 
final Group gCustomer = new Group("customerrelationship.lead.contact", LayoutHints.DEFAULT_SEPARATED_GROUP_HINTS);
gCustomer.addItem("ROLE", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
gCustomer.addItem("PHONE");
gCustomer.addItem("MOBILE");
gCustomer.addItem("FAX");
gCustomer.addItem("PHONE", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
gCustomer.addItem("MOBILE", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
gCustomer.addItem("FAX", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
gCustomer.addItem("EMAIL", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
gCustomer.addItem("WEBSITE", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
this.add(gCustomer);
 
final Group gAddress = new Group("customerrelationship.lead.address", LayoutHints.DEFAULT_SEPARATED_GROUP_HINTS);
gAddress.addItem("ID_ADRESSE");
gAddress.addItem("ID_ADRESSE", LayoutHints.DEFAULT_VERY_LARGE_FIELD_HINTS);
this.add(gAddress);
 
final Group gInfos = new Group("customerrelationship.lead.info");
gInfos.addItem("INFORMATION", new LayoutHints(true, true, true, true, true, true));
gInfos.addItem("INDUSTRY");
gInfos.addItem("REVENUE");
gInfos.addItem("EMPLOYEES");
gInfos.addItem("INFOS", new LayoutHints(true, true, true, true, true, true));
final Group gInfos = new Group("customerrelationship.lead.info", LayoutHints.DEFAULT_SEPARATED_GROUP_HINTS);
gInfos.addItem("INFORMATION", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
gInfos.addItem("INDUSTRY", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
gInfos.addItem("REVENUE", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
gInfos.addItem("EMPLOYEES", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
gInfos.addItem("INFOS", new LayoutHints(true, true, true, true, true, true, true, true));
this.add(gInfos);
 
final Group gState = new Group("customerrelationship.lead.state");
gState.addItem("RATING");
gState.addItem("SOURCE");
gState.addItem("STATUS");
gState.addItem("ID_COMMERCIAL");
gState.addItem("REMIND_DATE");
final Group gState = new Group("customerrelationship.lead.state", LayoutHints.DEFAULT_SEPARATED_GROUP_HINTS);
gState.addItem("RATING", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
gState.addItem("SOURCE", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
gState.addItem("STATUS", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
gState.addItem("ID_COMMERCIAL", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
gState.addItem("REMIND_DATE", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
UserRights rights = UserRightsManager.getCurrentUserRights();
if (rights.haveRight("CLIENT_PROSPECT")) {
gState.addItem("ID_CLIENT");
gState.addItem("ID_CLIENT", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
}
gState.addItem("DISPO");
 
gState.addItem("DISPO", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
this.add(gState);
 
final Group gItems = new Group("customerrelationship.lead.items.call.tab");
gItems.addItem("customerrelationship.lead.items.call", LayoutHints.DEFAULT_VERY_LARGE_TEXT_HINTS);
this.add(gItems);
 
final Group gItems2 = new Group("customerrelationship.lead.items.visit.tab");
gItems2.addItem("customerrelationship.lead.items.visit", LayoutHints.DEFAULT_VERY_LARGE_TEXT_HINTS);
this.add(gItems2);
 
}
 
public static void main(String[] args) {
/trunk/Modules/Module Lead/src/org/openconcerto/modules/customerrelationship/lead/call/CustomerCallSQLElement.java
15,6 → 15,7
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.ui.JDate;
import org.openconcerto.ui.JLabelBold;
import org.openconcerto.ui.component.ITextArea;
 
public class CustomerCallSQLElement extends ModuleElement {
 
27,6 → 28,11
final List<String> l = new ArrayList<String>();
l.add("DATE");
l.add("ID_CLIENT");
l.add("INFORMATION");
if (getTable().contains("ID_COMMERCIAL")) {
l.add("ID_COMMERCIAL");
}
return l;
}
 
54,10 → 60,8
@Override
public JComponent createEditor(String id) {
if (id.equals("INFORMATION")) {
final JTextArea jTextArea = new JTextArea();
jTextArea.setFont(new JLabel().getFont());
jTextArea.setMinimumSize(new Dimension(200, 150));
jTextArea.setPreferredSize(new Dimension(200, 150));
final ITextArea jTextArea = new ITextArea();
jTextArea.setRows(20);
return new JScrollPane(jTextArea);
} else if (id.equals("DATE")) {
return new JDate(true);
/trunk/Modules/Module Lead/src/org/openconcerto/modules/customerrelationship/lead/call/LeadCallSQLElement.java
7,7 → 7,6
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
 
import org.openconcerto.erp.modules.AbstractModule;
import org.openconcerto.erp.modules.ModuleElement;
15,6 → 14,7
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.ui.JDate;
import org.openconcerto.ui.JLabelBold;
import org.openconcerto.ui.component.ITextArea;
 
public class LeadCallSQLElement extends ModuleElement {
 
27,6 → 27,11
final List<String> l = new ArrayList<String>();
l.add("DATE");
l.add("ID_LEAD");
l.add("INFORMATION");
if (getTable().contains("ID_COMMERCIAL")) {
l.add("ID_COMMERCIAL");
}
 
return l;
}
 
45,7 → 50,7
public JComponent getLabel(String id) {
if (id.equals("customerrelationship.lead.call.content")) {
return new JLabelBold("Description de l'appel téléphonique");
}else if (id.equals("customerrelationship.lead.call.next")) {
} else if (id.equals("customerrelationship.lead.call.next")) {
return new JLabelBold("Suite à donner");
}
return super.getLabel(id);
54,10 → 59,8
@Override
public JComponent createEditor(String id) {
if (id.equals("INFORMATION")) {
final JTextArea jTextArea = new JTextArea();
jTextArea.setFont(new JLabel().getFont());
jTextArea.setMinimumSize(new Dimension(200, 150));
jTextArea.setPreferredSize(new Dimension(200, 150));
final ITextArea jTextArea = new ITextArea();
jTextArea.setRows(20);
return new JScrollPane(jTextArea);
} else if (id.equals("DATE")) {
return new JDate(true);
/trunk/Modules/Module Lead/src/org/openconcerto/modules/customerrelationship/lead/LeadSQLElement.java
4,6 → 4,7
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Set;
54,6 → 55,38
super(module, Module.TABLE_LEAD);
 
// Call
final RowAction.PredicateRowAction addDuplicateAction = new RowAction.PredicateRowAction(new AbstractAction("Créer à partir de") {
 
@Override
public void actionPerformed(ActionEvent e) {
SQLRow sRow = IListe.get(e).getSelectedRow().asRow();
final SQLTable table = LeadSQLElement.this.getTable().getTable(Module.TABLE_LEAD);
final SQLElement leadElt = LeadSQLElement.this.getDirectory().getElement(table);
EditFrame editFrame = new EditFrame(leadElt);
final SQLRowValues sqlRowValues = new SQLRowValues(table);
sqlRowValues.put("COMPANY", sRow.getObject("COMPANY"));
sqlRowValues.put("PHONE", sRow.getObject("PHONE"));
sqlRowValues.put("FAX", sRow.getObject("FAX"));
sqlRowValues.put("WEBSITE", sRow.getObject("WEBSITE"));
sqlRowValues.put("DATE", new Date());
SQLRowValues adr = new SQLRowValues(sRow.getForeign("ID_ADRESSE").asRowValues());
sqlRowValues.put("ID_ADRESSE", adr);
sqlRowValues.put("INDUSTRY", sRow.getObject("INDUSTRY"));
sqlRowValues.put("REVENUE", sRow.getObject("REVENUE"));
sqlRowValues.put("EMPLOYEES", sRow.getObject("EMPLOYEES"));
sqlRowValues.put("LOCALISATION", sRow.getObject("LOCALISATION"));
sqlRowValues.put("SIRET", sRow.getObject("SIRET"));
sqlRowValues.put("APE", sRow.getObject("APE"));
 
editFrame.getSQLComponent().select(sqlRowValues);
FrameUtil.show(editFrame);
}
}, true) {
};
addDuplicateAction.setPredicate(IListeEvent.getSingleSelectionPredicate());
getRowActions().add(addDuplicateAction);
 
// Call
final RowAction.PredicateRowAction addCallAction = new RowAction.PredicateRowAction(new AbstractAction("Appeler") {
 
@Override
121,6 → 154,79
}
}
 
if (getTable().contains("MODIFICATION_DATE")) {
BaseSQLTableModelColumn dateM = new BaseSQLTableModelColumn("Date de modification", Date.class) {
 
@Override
protected Object show_(SQLRowAccessor r) {
return r.getObject("MODIFICATION_DATE");
}
 
@Override
public Set<FieldPath> getPaths() {
Path p = new Path(getTable());
return CollectionUtils.createSet(new FieldPath(p, "MODIFICATION_DATE"));
}
};
source.getColumns().add(1, dateM);
}
 
BaseSQLTableModelColumn dateV = new BaseSQLTableModelColumn("Visite", Date.class) {
 
@Override
protected Object show_(SQLRowAccessor r) {
Date d = null;
Collection<? extends SQLRowAccessor> l = r.getReferentRows(r.getTable().getTable("LEAD_VISIT"));
for (SQLRowAccessor sqlRowAccessor : l) {
if (d != null && sqlRowAccessor.getObject("DATE") != null && d.before(sqlRowAccessor.getDate("DATE").getTime())) {
d = sqlRowAccessor.getDate("DATE").getTime();
} else {
if (d == null && sqlRowAccessor.getObject("DATE") != null) {
d = sqlRowAccessor.getDate("DATE").getTime();
}
}
 
}
return d;
}
 
@Override
public Set<FieldPath> getPaths() {
Path p = new Path(getTable());
p = p.add(p.getLast().getTable("LEAD_VISIT"));
return CollectionUtils.createSet(new FieldPath(p, "DATE"));
}
};
source.getColumns().add(1, dateV);
 
BaseSQLTableModelColumn dateA = new BaseSQLTableModelColumn("Appel", Date.class) {
 
@Override
protected Object show_(SQLRowAccessor r) {
Date d = null;
Collection<? extends SQLRowAccessor> l = r.getReferentRows(r.getTable().getTable("LEAD_CALL"));
for (SQLRowAccessor sqlRowAccessor : l) {
if (d != null && sqlRowAccessor.getObject("DATE") != null && d.before(sqlRowAccessor.getDate("DATE").getTime())) {
d = sqlRowAccessor.getDate("DATE").getTime();
} else {
if (d == null && sqlRowAccessor.getObject("DATE") != null) {
d = sqlRowAccessor.getDate("DATE").getTime();
}
}
 
}
return d;
}
 
@Override
public Set<FieldPath> getPaths() {
Path p = new Path(getTable());
p = p.add(p.getLast().getTable("LEAD_CALL"));
return CollectionUtils.createSet(new FieldPath(p, "DATE"));
}
};
source.getColumns().add(1, dateA);
 
BaseSQLTableModelColumn adresse = new BaseSQLTableModelColumn("Adresse", String.class) {
 
@Override
189,6 → 295,32
};
source.getColumns().add(ville);
 
BaseSQLTableModelColumn dpt = new BaseSQLTableModelColumn("Département", String.class) {
 
@Override
protected Object show_(SQLRowAccessor r) {
 
String s = r.getForeign("ID_ADRESSE").getString("CODE_POSTAL");
if (s != null && s.length() >= 2) {
return s.substring(0, 2);
} else {
return s;
}
 
}
 
@Override
public Set<FieldPath> getPaths() {
Path p = new Path(getTable());
final SQLTable clientT = getTable().getForeignTable("ID_CLIENT");
p = p.add(clientT);
p = p.add(clientT.getField("ID_ADRESSE"));
return CollectionUtils.createSet(new FieldPath(p, "VILLE"), new FieldPath(p, "CODE_POSTAL"));
}
};
 
source.getColumns().add(dpt);
 
if (getTable().contains("REMIND_DATE")) {
BaseSQLTableModelColumn dateRemind = new BaseSQLTableModelColumn("Date de rappel", Date.class) {
 
/trunk/Modules/Module Lead/src/org/openconcerto/modules/customerrelationship/lead/translation_fr.xml
New file
0,0 → 1,4
<translation lang="fr">
<item id="customerrelationship.lead.items.call.tab" label="Appels" />
<item id="customerrelationship.lead.items.visit.tab" label="Visites" />
</translation>
/trunk/Modules/Module Lead/src/org/openconcerto/modules/customerrelationship/lead/LeadCustomerSQLInjector.java
3,6 → 3,8
*/
package org.openconcerto.modules.customerrelationship.lead;
 
import java.util.Date;
 
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLInjector;
import org.openconcerto.sql.model.SQLRowAccessor;
26,6 → 28,8
map(leadTable.getField("MOBILE"), customerTable.getField("TEL_P"));
// map(leadTable.getField("INFORMATION"), customerTable.getField("INFOS"));
map(getSource().getField("INFOS"), getDestination().getField("INFOS"));
remove(leadTable.getField("DATE"), customerTable.getField("DATE"));
mapDefaultValues(customerTable.getField("DATE"), new Date());
remove(leadTable.getField("ID_ADRESSE"), customerTable.getField("ID_ADRESSE"));
}
 
/trunk/Modules/Module Lead/src/org/openconcerto/modules/customerrelationship/lead/LeadSQLComponent.java
5,13 → 5,17
 
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JTextField;
 
import org.openconcerto.modules.customerrelationship.lead.visit.LeadActionItemTable;
import org.openconcerto.sql.element.GroupSQLComponent;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLBackgroundTableCache;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.sql.sqlobject.SQLSearchableTextCombo;
import org.openconcerto.sql.users.UserManager;
import org.openconcerto.ui.JDate;
21,8 → 25,12
import org.openconcerto.ui.group.Group;
 
public class LeadSQLComponent extends GroupSQLComponent {
 
private LeadActionItemTable tableCall, tableVisit;
 
public LeadSQLComponent(SQLElement element, Group group) {
super(element, group);
startTabGroupAfter("customerrelationship.lead.state");
}
 
@Override
37,10 → 45,26
public JComponent getLabel(String id) {
if (id.equals("customerrelationship.lead.person")) {
return new JLabelBold("Contact");
}
if (id.equals("customerrelationship.lead.items.visit.tab")) {
return new JLabelBold("Visites");
}
if (id.equals("customerrelationship.lead.items.visit")) {
return new JLabelBold("");
}
if (id.equals("customerrelationship.lead.items.call.tab")) {
return new JLabelBold("Appels");
}
if (id.equals("customerrelationship.lead.items.call")) {
return new JLabelBold("");
} else if (id.equals("customerrelationship.lead.contact")) {
return new JLabel();
} else if (id.equals("customerrelationship.lead.address")) {
return new JLabelBold("Adresse");
} else if (id.equals("customerrelationship.lead.info")) {
return new JLabelBold("Infos");
} else if (id.equals("customerrelationship.lead.state")) {
return new JLabelBold("Statut");
} else {
return super.getLabel(id);
}
48,20 → 72,61
 
@Override
public JComponent createEditor(String id) {
 
if (id.equals("INFORMATION") || id.equals("INFOS")) {
final ITextArea jTextArea = new ITextArea();
final ITextArea jTextArea = new ITextArea(3,3);
jTextArea.setFont(new JLabel().getFont());
return jTextArea;
} else if (id.equals("ID_COMMERCIAL") || id.equals("ID_TITRE_PERSONNEL")) {
ElementComboBox comp = new ElementComboBox(false, 1);
((ElementComboBox) comp).init(getElement().getForeignElement(id));
return comp;
} else if (id.equals("customerrelationship.lead.items.call")) {
tableCall = new LeadActionItemTable(getElement().getDirectory().getElement(Module.TABLE_LEAD_CALL));
return tableCall;
} else if (id.equals("customerrelationship.lead.items.visit")) {
tableVisit = new LeadActionItemTable(getElement().getDirectory().getElement(Module.TABLE_LEAD_VISIT));
return tableVisit;
} else if (id.equals("INDUSTRY") || id.equals("STATUS") || id.equals("RATING") || id.equals("SOURCE") || id.equals("DISPO")) {
return new SQLSearchableTextCombo(ComboLockedMode.UNLOCKED, 1, 20, false);
return new SQLSearchableTextCombo(ComboLockedMode.UNLOCKED, 1, 1, false);
} else if (id.equals("DATE")) {
return new JDate(true);
}
return super.createEditor(id);
JComponent comp = super.createEditor(id);
if(comp.getClass() == JTextField.class) {
JTextField jtxt = new JTextField(10);
comp = jtxt;
}
return comp;
}
 
@Override
public int insert(SQLRow order) {
int id = super.insert(order);
this.tableCall.updateField("ID_LEAD", id);
this.tableVisit.updateField("ID_LEAD", id);
return id;
}
 
@Override
public void select(SQLRowAccessor r) {
super.select(r);
if (r != null) {
this.tableCall.insertFrom("ID_LEAD", r.getID());
this.tableVisit.insertFrom("ID_LEAD", r.getID());
}
}
 
@Override
public void update() {
super.update();
this.tableCall.updateField("ID_LEAD", getSelectedID());
this.tableVisit.updateField("ID_LEAD", getSelectedID());
}
 
@Override
protected SQLRowValues createDefaults() {
SQLRowValues rowVals = new SQLRowValues(getTable());
rowVals.put("STATUS", "Nouveau");
/trunk/Modules/Module Lead/src/org/openconcerto/modules/customerrelationship/lead/labels_fr.xml
38,6 → 38,7
name="rapport d'appel prospect" namePlural="rapports d'appel prospect">
<FIELD name="DATE" label="Date de l'appel" />
<FIELD name="ID_LEAD" label="Entreprise" />
<FIELD name="ID_COMMERCIAL" label="Commercial" />
<FIELD name="INFORMATION" label="Résumé de l'appel" />
<FIELD name="NEXTCONTACT_DATE" label="Date de prochain contact" />
<FIELD name="NEXTCONTACT_INFO" label="Motif de prochain contact" />
47,6 → 48,7
</element>
<element refid="org.openconcerto.modules.customerrelationship.lead/CUSTOMER_CALL" nameClass="masculine"
name="rapport d'appel client" namePlural="rapports d'appel client">
<FIELD name="ID_COMMERCIAL" label="Commercial" />
<FIELD name="DATE" label="Date de l'appel" />
<FIELD name="ID_CLIENT" label="Client" />
<FIELD name="INFORMATION" label="Résumé de l'appel" />
/trunk/Modules/Module Project/src/org/openconcerto/modules/project/Module.java
94,7 → 94,6
import org.openconcerto.utils.Tuple2;
import org.openconcerto.utils.cc.IExnClosure;
import org.openconcerto.utils.cc.ITransformer;
import org.openconcerto.utils.i18n.TranslationManager;
 
public final class Module extends AbstractModule {
 
191,7 → 190,6
@Override
protected void setupElements(final SQLElementDirectory dir) {
super.setupElements(dir);
TranslationManager.getInstance().addTranslationStreamFromClass(this.getClass());
dir.addSQLElement(ProjectSQLElement.class);
dir.addSQLElement(ProjectStateSQLElement.class);
dir.addSQLElement(ProjectTypeSQLElement.class);
607,7 → 605,7
protected void setupComponents(final ComponentsContext ctxt) {
 
DBRoot root = ComptaPropsConfiguration.getInstanceCompta().getRootSociete();
List<String> table2check = Arrays.asList("BON_RECEPTION", "DEMANDE_PRIX", "DEMANDE_ACHAT_ELEMENT");
List<String> table2check = Arrays.asList("BON_RECEPTION", "DEMANDE_PRIX", "DEMANDE_ACHAT_ELEMENT", "FACTURE_FOURNISSEUR");
for (String table : table2check) {
if (root.contains(table)) {
SQLTable tableCR = root.getTable(table);
/trunk/Modules/Module Expense/src/org/openconcerto/modules/humanresources/travel/expense/ExpenseGroup.java
6,33 → 6,32
 
public class ExpenseGroup extends Group {
 
public ExpenseGroup() {
super(ExpenseSQLElement.ELEMENT_CODE + ".default");
final Group g = new Group(ExpenseSQLElement.ELEMENT_CODE + ".identifier");
g.addItem("DATE");
g.addItem("ID_USER_COMMON");
public ExpenseGroup() {
super(ExpenseSQLElement.ELEMENT_CODE + ".default", LayoutHints.DEFAULT_SEPARATED_GROUP_HINTS);
final Group g = new Group(ExpenseSQLElement.ELEMENT_CODE + ".identifier");
g.addItem("DATE", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
g.addItem("ID_USER_COMMON", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
 
this.add(g);
this.add(g);
 
final Group gDescription = new Group(ExpenseSQLElement.ELEMENT_CODE + ".description");
gDescription.add(new Item("DESCRIPTION", new LayoutHints(true, true, true, true, true, true)));
this.add(gDescription);
final Group gDescription = new Group(ExpenseSQLElement.ELEMENT_CODE + ".description");
gDescription.addItem("DESCRIPTION", new LayoutHints(true, true, true, true, true, true, true, true));
gDescription.addItem("ID_EXPENSE_STATE", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
this.add(gDescription);
 
final Group gTravel = new Group(ExpenseSQLElement.ELEMENT_CODE + ".travel", LayoutHints.DEFAULT_SEPARATED_GROUP_HINTS);
gTravel.addItem("TRAVEL_DISTANCE");
gTravel.addItem("TRAVEL_RATE");
gTravel.addItem("TRAVEL_AMOUNT");
this.add(gTravel);
final Group gTravel = new Group(ExpenseSQLElement.ELEMENT_CODE + ".travel",
LayoutHints.DEFAULT_SEPARATED_GROUP_HINTS);
gTravel.addItem("TRAVEL_DISTANCE", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
gTravel.addItem("TRAVEL_RATE", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
gTravel.addItem("TRAVEL_AMOUNT", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
this.add(gTravel);
 
final Group gAddress = new Group(ExpenseSQLElement.ELEMENT_CODE + ".misc", LayoutHints.DEFAULT_SEPARATED_GROUP_HINTS);
gAddress.addItem("MISC_AMOUNT");
this.add(gAddress);
final Group gAddress = new Group(ExpenseSQLElement.ELEMENT_CODE + ".misc",
LayoutHints.DEFAULT_SEPARATED_GROUP_HINTS);
gAddress.addItem("MISC_AMOUNT", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
// gAddress.addItem("ID_EXPENSE_STATE", LayoutHints.DEFAULT_LARGE_FIELD_HINTS);
this.add(gAddress);
 
final Group gState = new Group(ExpenseSQLElement.ELEMENT_CODE + ".state");
gState.addItem("ID_EXPENSE_STATE");
}
 
this.add(gState);
 
}
 
}
/trunk/Modules/Module Expense/src/org/openconcerto/modules/humanresources/travel/expense/translation_fr.xml
New file
0,0 → 1,5
<translation lang="fr">
<item id="humanresources.travel.expense.travel" label="Frais kilometriques" />
<item id="humanresources.travel.expense.misc" label="Frais annexes" />
<item id="humanresources.travel.expense.default" label="Description" />
</translation>
/trunk/Modules/Module Expense/src/org/openconcerto/modules/humanresources/travel/expense/labels_fr.xml
1,7 → 1,7
<?xml version="1.0" encoding="UTF-8" ?>
<ROOT>
<TABLE name="EXPENSE_STATE">
<FIELD name="NAME" label="Nom" />
<FIELD name="NAME" label="Statut" />
</TABLE>
<TABLE name="EXPENSE">
<FIELD name="NAME" label="Nom" />
12,9 → 12,9
<FIELD name="TRAVEL_RATE" label="Tarif kilométrique" />
<FIELD name="TRAVEL_AMOUNT" label="Montant des frais kilométriques" />
<FIELD name="MISC_AMOUNT" label="Montant des frais annexes" />
<FIELD name="ID_EXPENSE_STATE" label="Status" />
<FIELD name="ID_EXPENSE_STATE" label="Statut" />
<FIELD name="ID_USER_COMMON" label="Employé" />
<FIELD name="ID_EXPENSE_STATE" label="Status" />
<FIELD name="ID_EXPENSE_STATE" label="Statut" />
</TABLE>
 
</ROOT>
/trunk/Modules/Module Expense/src/org/openconcerto/modules/humanresources/travel/expense/ExpenseSQLComponent.java
7,6 → 7,7
import java.util.Set;
 
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.text.AbstractDocument;
import javax.swing.text.JTextComponent;
 
13,9 → 14,10
import org.openconcerto.erp.core.common.ui.DeviseField;
import org.openconcerto.sql.element.GroupSQLComponent;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.sql.sqlobject.itemview.VWRowItemView;
import org.openconcerto.ui.JDate;
import org.openconcerto.ui.component.ITextArea;
import org.openconcerto.ui.JLabelBold;
import org.openconcerto.ui.component.text.TextComponentUtils;
import org.openconcerto.ui.group.Group;
import org.openconcerto.utils.text.DocumentFilterList;
23,73 → 25,91
import org.openconcerto.utils.text.LimitedSizeDocumentFilter;
 
public class ExpenseSQLComponent extends GroupSQLComponent {
private DecimalFormat decimalFormat = new DecimalFormat("0.##");
private DecimalFormat decimalFormat = new DecimalFormat("0.##");
 
public ExpenseSQLComponent(SQLElement element, Group group) {
super(element, group);
public ExpenseSQLComponent(SQLElement element, Group group) {
super(element, group);
 
}
}
 
@Override
protected void initDone() {
super.initDone();
final PropertyChangeListener listener = new PropertyChangeListener() {
@Override
protected void initDone() {
super.initDone();
final PropertyChangeListener listener = new PropertyChangeListener() {
 
@Override
public void propertyChange(PropertyChangeEvent evt) {
updateAmount();
}
};
@Override
public void propertyChange(PropertyChangeEvent evt) {
updateAmount();
}
};
 
final AbstractDocument comp1 = (AbstractDocument) TextComponentUtils.getDocument(getView("TRAVEL_DISTANCE").getComp());
DocumentFilterList.add(comp1, new LimitedSizeDocumentFilter(5), FilterType.SIMPLE_FILTER);
getView("TRAVEL_DISTANCE").addValueListener(listener);
final AbstractDocument comp1 = (AbstractDocument) TextComponentUtils
.getDocument(getView("TRAVEL_DISTANCE").getComp());
DocumentFilterList.add(comp1, new LimitedSizeDocumentFilter(5), FilterType.SIMPLE_FILTER);
getView("TRAVEL_DISTANCE").addValueListener(listener);
 
final AbstractDocument comp2 = (AbstractDocument) TextComponentUtils.getDocument(getView("TRAVEL_RATE").getComp());
DocumentFilterList.add(comp2, new LimitedSizeDocumentFilter(5), FilterType.SIMPLE_FILTER);
final AbstractDocument comp2 = (AbstractDocument) TextComponentUtils
.getDocument(getView("TRAVEL_RATE").getComp());
DocumentFilterList.add(comp2, new LimitedSizeDocumentFilter(5), FilterType.SIMPLE_FILTER);
 
getView("TRAVEL_RATE").addValueListener(listener);
}
getView("TRAVEL_RATE").addValueListener(listener);
}
 
@Override
protected Set<String> createRequiredNames() {
final Set<String> s = new HashSet<String>(1);
s.add("DATE");
s.add("DESCRIPTION");
s.add("ID_USER_COMMON");
s.add("ID_EXPENSE_STATE");
return s;
}
@Override
protected Set<String> createRequiredNames() {
final Set<String> s = new HashSet<String>(1);
s.add("DATE");
s.add("DESCRIPTION");
s.add("ID_USER_COMMON");
s.add("ID_EXPENSE_STATE");
return s;
}
 
@Override
public JComponent getEditor(String id) {
if (id.equals("DESCRIPTION")) {
return new ITextArea();
} else if (id.equals("DATE")) {
return new JDate(true);
} else if (id.endsWith("AMOUNT")) {
return new DeviseField();
}
return super.getEditor(id);
}
@Override
public JComponent createEditor(String id) {
if(id.equals("ID_USER_COMMON") || id.equals("ID_EXPENSE_STATE")) {
ElementComboBox comp = new ElementComboBox(false, 15);
((ElementComboBox) comp).init(getElement().getForeignElement(id));
return comp;
}
else if (id.equals("DATE")) {
return new JDate(true);
} else if (id.endsWith("AMOUNT")) {
return new DeviseField();
}
return super.createEditor(id);
}
 
private void updateAmount() {
float v1 = getFloat("TRAVEL_DISTANCE");
float v2 = getFloat("TRAVEL_RATE");
float total = v1 * v2;
if (total > 1000000 || total < 0) {
total = 0;
}
final String valueOf = decimalFormat.format(total);
((JTextComponent) getView("TRAVEL_AMOUNT").getComp()).setText(valueOf);
}
@Override
public JLabel getLabel(String id) {
if (id.equals("humanresources.travel.expense.travel")) {
return new JLabelBold("Frais kilometriques");
} else if (id.equals("humanresources.travel.expense.default")) {
return new JLabelBold("Descriptif");
} else if (id.equals("humanresources.travel.expense.misc")) {
return new JLabelBold("Frais annexes");
} else {
return (JLabel) super.getLabel(id);
}
}
 
private float getFloat(String id) {
final Number n = (Number) ((VWRowItemView<?>) getView(id)).getWrapper().getValue();
if (n == null) {
return 0;
}
return n.floatValue();
}
private void updateAmount() {
float v1 = getFloat("TRAVEL_DISTANCE");
float v2 = getFloat("TRAVEL_RATE");
float total = v1 * v2;
if (total > 1000000 || total < 0) {
total = 0;
}
final String valueOf = decimalFormat.format(total);
((JTextComponent) getView("TRAVEL_AMOUNT").getComp()).setText(valueOf);
}
 
private float getFloat(String id) {
final Number n = (Number) ((VWRowItemView<?>) getView(id)).getWrapper().getValue();
if (n == null) {
return 0;
}
return n.floatValue();
}
 
}
/trunk/Modules/Module Expense/src/org/openconcerto/modules/humanresources/travel/expense/ExpenseSQLElement.java
54,7 → 54,7
}
 
@Override
public SQLComponent createComponent() {
public SQLComponent createComponent() {
final String groupId = this.getCode() + ".default";
final Group group = GlobalMapper.getInstance().getGroup(groupId);
if (group == null) {
/trunk/Modules/Module Batch Processing/src/org/openconcerto/modules/common/batchprocessing/StringProcessor.java
29,8 → 29,8
private JRadioButton bLower;
private JRadioButton bUpper;
 
public StringProcessor(SQLField field) {
this.field = field;
public StringProcessor(BatchField field) {
this.field = field.getField();
 
this.setLayout(new GridBagLayout());
bReplace = new JRadioButton("remplacer par");
/trunk/Modules/Module Batch Processing/src/org/openconcerto/modules/common/batchprocessing/BatchEditorPanel.java
24,10 → 24,13
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
 
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.PropsConfiguration;
import org.openconcerto.sql.element.SQLElementDirectory;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowListRSH;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.request.SQLFieldTranslator;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.JLabelBold;
36,24 → 39,34
 
public class BatchEditorPanel extends JPanel {
 
public BatchEditorPanel(final List<SQLRowValues> rows, FieldFilter filter) {
Configuration conf = PropsConfiguration.getInstance();
final SQLFieldTranslator translator = conf.getTranslator();
public BatchEditorPanel(final SQLElementDirectory dir, final List<SQLRowValues> rows, FieldFilter filter) {
SQLFieldTranslator translator = dir.getTranslator();
Set<SQLField> fields = rows.get(0).getTable().getFields();
List<SQLField> f = new ArrayList<SQLField>();
List<BatchField> f = new ArrayList<BatchField>();
for (SQLField sqlField : fields) {
if (ForbiddenFieldName.isAllowed(sqlField.getName()) && translator.getLabelFor(sqlField) != null) {
if (filter == null || !filter.isFiltered(sqlField)) {
f.add(sqlField);
f.add(new BatchField(dir, sqlField, null));
}
}
}
SQLTable tableTarif = rows.get(0).getTable().getTable("TARIF");
SQLTable tableArticleTarif = rows.get(0).getTable().getTable("ARTICLE_TARIF");
SQLSelect sel = new SQLSelect();
sel.addSelectStar(tableTarif);
List<SQLRow> rowTarif = SQLRowListRSH.execute(sel);
for (SQLRow sqlRow : rowTarif) {
f.add(new BatchField(dir, tableArticleTarif.getField("PV_HT"), sqlRow));
if (tableArticleTarif.contains("POURCENT_REMISE")) {
f.add(new BatchField(dir, tableArticleTarif.getField("POURCENT_REMISE"), sqlRow));
}
}
 
Collections.sort(f, new Comparator<SQLField>() {
Collections.sort(f, new Comparator<BatchField>() {
 
@Override
public int compare(SQLField o1, SQLField o2) {
return translator.getLabelFor(o1).compareToIgnoreCase(translator.getLabelFor(o2));
public int compare(BatchField o1, BatchField o2) {
return o1.getComboName().compareToIgnoreCase(o2.getComboName());
}
});
this.setLayout(new GridBagLayout());
60,11 → 73,11
GridBagConstraints c = new DefaultGridBagConstraints();
this.add(new JLabel("Champ"), c);
 
final JComboBox<SQLField> combo = new JComboBox<SQLField>(f.toArray(new SQLField[1]));
final JComboBox<BatchField> combo = new JComboBox<BatchField>(f.toArray(new BatchField[1]));
combo.setRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
String label = translator.getLabelFor(((SQLField) value));
String label = ((BatchField) value).getComboName();
return super.getListCellRendererComponent(list, label, index, isSelected, cellHasFocus);
}
});
86,7 → 99,7
c.gridy++;
c.anchor = GridBagConstraints.NORTHWEST;
final BatchDetailPanel comp = new BatchDetailPanel();
comp.setField((SQLField) combo.getSelectedItem());
comp.setField((BatchField) combo.getSelectedItem());
this.add(comp, c);
 
JPanel actions = new JPanel();
108,7 → 121,7
 
@Override
public void itemStateChanged(ItemEvent e) {
comp.setField((SQLField) combo.getSelectedItem());
comp.setField((BatchField) combo.getSelectedItem());
 
}
});
/trunk/Modules/Module Batch Processing/src/org/openconcerto/modules/common/batchprocessing/DateProcessor.java
17,8 → 17,8
private final JDate d = new JDate(true);
private final SQLField field;
 
public DateProcessor(SQLField field) {
this.field = field;
public DateProcessor(BatchField field) {
this.field = field.getField();
this.setLayout(new FlowLayout());
this.add(new JLabel("forcer la date au "));
this.add(d);
/trunk/Modules/Module Batch Processing/src/org/openconcerto/modules/common/batchprocessing/BooleanProcessor.java
13,13 → 13,13
import org.openconcerto.ui.VFlowLayout;
 
public class BooleanProcessor extends JPanel implements BatchProcessor {
private final SQLField field;
private final BatchField field;
 
private JRadioButton bTrue;
private JRadioButton bFalse;
private JRadioButton bInvert;
 
public BooleanProcessor(SQLField field) {
public BooleanProcessor(BatchField field) {
this.field = field;
this.setLayout(new VFlowLayout());
bTrue = new JRadioButton("forcer à vrai");
41,7 → 41,7
if (bTrue.isSelected()) {
for (SQLRowAccessor sqlRowAccessor : r) {
final SQLRowValues rowValues = sqlRowAccessor.createEmptyUpdateRow();
rowValues.put(field.getName(), Boolean.TRUE);
rowValues.put(field.getField().getName(), Boolean.TRUE);
processBeforeUpdate(sqlRowAccessor, rowValues);
rowValues.update();
}
48,7 → 48,7
} else if (bFalse.isSelected()) {
for (SQLRowAccessor sqlRowAccessor : r) {
final SQLRowValues rowValues = sqlRowAccessor.createEmptyUpdateRow();
rowValues.put(field.getName(), Boolean.FALSE);
rowValues.put(field.getField().getName(), Boolean.FALSE);
processBeforeUpdate(sqlRowAccessor, rowValues);
rowValues.update();
}
55,9 → 55,9
} else if (bInvert.isSelected()) {
for (SQLRowAccessor sqlRowAccessor : r) {
final SQLRowValues rowValues = sqlRowAccessor.createEmptyUpdateRow();
final Boolean boolean1 = sqlRowAccessor.asRow().getBoolean(field.getName());
final Boolean boolean1 = sqlRowAccessor.asRow().getBoolean(field.getField().getName());
if (boolean1 != null) {
rowValues.put(field.getName(), boolean1.equals(Boolean.FALSE));
rowValues.put(field.getField().getName(), boolean1.equals(Boolean.FALSE));
processBeforeUpdate(sqlRowAccessor, rowValues);
rowValues.update();
}
/trunk/Modules/Module Batch Processing/src/org/openconcerto/modules/common/batchprocessing/BatchDetailPanel.java
22,46 → 22,47
this.setLayout(new VFlowLayout());
}
 
public void setField(SQLField field) {
public void setField(BatchField batchField) {
this.removeAll();
 
SQLField field = batchField.getField();
final SQLType type = field.getType();
final Class<?> javaType = type.getJavaType();
final String fName = field.getName();
if (fName.equals("PV_TTC")) {
final NumberProcessor p = new TTCProcessor(field);
final NumberProcessor p = new TTCProcessor(batchField);
this.add(p);
this.processor = p;
} else if (fName.equals("PV_HT")) {
final NumberProcessor p = new HTProcessor(field);
final NumberProcessor p = new HTProcessor(batchField);
this.add(p);
this.processor = p;
} else if (fName.equals("ID_TAXE")) {
final ReferenceProcessor p = new TVAProcessor(field);
final ReferenceProcessor p = new TVAProcessor(batchField);
this.add(p);
this.processor = p;
} else if (fName.equals("PA_HT")) {
final NumberProcessor p = new PurchaseProcessor(field);
final NumberProcessor p = new PurchaseProcessor(batchField);
this.add(p);
this.processor = p;
} else if (javaType.equals(Boolean.class)) {
final BooleanProcessor p = new BooleanProcessor(field);
final BooleanProcessor p = new BooleanProcessor(batchField);
this.add(p);
this.processor = p;
} else if (field.isKey()) {
final ReferenceProcessor p = new ReferenceProcessor(field);
final ReferenceProcessor p = new ReferenceProcessor(batchField);
this.add(p);
this.processor = p;
} else if (javaType.equals(String.class)) {
final StringProcessor p = new StringProcessor(field);
final StringProcessor p = new StringProcessor(batchField);
this.add(p);
this.processor = p;
} else if (javaType.equals(Date.class)) {
final DateProcessor p = new DateProcessor(field);
final DateProcessor p = new DateProcessor(batchField);
this.add(p);
this.processor = p;
} else if (javaType.equals(BigDecimal.class) || javaType.equals(Float.class) || javaType.equals(Double.class) || javaType.equals(Integer.class) || javaType.equals(Long.class)) {
final NumberProcessor p = new NumberProcessor(field);
final NumberProcessor p = new NumberProcessor(batchField);
this.add(p);
this.processor = p;
}
/trunk/Modules/Module Batch Processing/src/org/openconcerto/modules/common/batchprocessing/BatchField.java
New file
0,0 → 1,58
package org.openconcerto.modules.common.batchprocessing;
 
import java.util.List;
 
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.element.SQLElementDirectory;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowListRSH;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.request.SQLFieldTranslator;
 
public class BatchField {
 
private final SQLField field;
private final SQLRowAccessor foreignLinkRow;
private final SQLFieldTranslator translator;
private final SQLElement elementLink;
 
public BatchField(SQLElementDirectory dir, SQLField field, SQLRowAccessor foreignLinkRow) {
this.field = field;
this.foreignLinkRow = foreignLinkRow;
 
this.translator = dir.getTranslator();
if (foreignLinkRow == null) {
this.elementLink = null;
} else {
this.elementLink = dir.getElement(foreignLinkRow.getTable());
}
}
 
public SQLField getField() {
return field;
}
 
public SQLRowAccessor getForeignLinkRow() {
return foreignLinkRow;
}
 
public String getComboName() {
if (this.foreignLinkRow == null) {
return this.translator.getLabelFor(this.field);
} else {
return this.elementLink.getPluralName() + " " + this.foreignLinkRow.getString("NOM") + " " + this.translator.getLabelFor(this.field);
}
}
 
public List<SQLRow> getReferentRows(SQLRowAccessor rowOrigin) {
SQLSelect sel = new SQLSelect();
sel.addSelectStar(this.field.getTable());
final Where w = new Where(this.field.getTable().getField("ID_" + rowOrigin.getTable().getName()), "=", rowOrigin.getID());
sel.setWhere(w.and(new Where(this.field.getTable().getField("ID_" + foreignLinkRow.getTable().getName()), "=", foreignLinkRow.getID())));
return SQLRowListRSH.execute(sel);
}
 
}
/trunk/Modules/Module Batch Processing/src/org/openconcerto/modules/common/batchprocessing/Module.java
2,7 → 2,6
 
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.util.List;
 
9,18 → 8,12
import javax.swing.AbstractAction;
import javax.swing.JFrame;
 
import org.openconcerto.erp.config.Gestion;
import org.openconcerto.erp.modules.AbstractModule;
import org.openconcerto.erp.modules.ComponentsContext;
import org.openconcerto.erp.modules.ModuleFactory;
import org.openconcerto.erp.modules.ModuleManager;
import org.openconcerto.erp.modules.ModulePackager;
import org.openconcerto.erp.modules.RuntimeModuleFactory;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRequestLog;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.ui.ConnexionPanel;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
import org.openconcerto.sql.view.list.RowAction;
33,7 → 26,7
}
 
@Override
protected void setupComponents(ComponentsContext ctxt) {
protected void setupComponents(final ComponentsContext ctxt) {
 
super.setupComponents(ctxt);
final SQLElement element = ctxt.getElement("ARTICLE");
60,7 → 53,7
 
};
 
f.setContentPane(new BatchEditorPanel(rows, filter));
f.setContentPane(new BatchEditorPanel(ctxt.getElement("ARTICLE").getDirectory(), rows, filter));
f.pack();
f.setMinimumSize(new Dimension(400, 300));
f.setLocationRelativeTo(IListe.get(e));
/trunk/Modules/Module Batch Processing/src/org/openconcerto/modules/common/batchprocessing/NumberProcessor.java
13,7 → 13,7
import javax.swing.JRadioButton;
import javax.swing.JTextField;
 
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.ui.DefaultGridBagConstraints;
20,7 → 20,7
 
public class NumberProcessor extends JPanel implements BatchProcessor {
 
private final SQLField field;
private final BatchField batchfield;
// Editors
final JTextField tReplace = new JTextField();
private JRadioButton bReplace;
30,8 → 30,8
final JTextField tRemove = new JTextField();
private JRadioButton bRemove;
 
public NumberProcessor(SQLField field) {
this.field = field;
public NumberProcessor(BatchField field) {
this.batchfield = field;
 
this.setLayout(new GridBagLayout());
bReplace = new JRadioButton("remplacer par");
110,10 → 110,22
if (bReplace.isSelected()) {
BigDecimal v = new BigDecimal(this.tReplace.getText().trim());
for (SQLRowAccessor sqlRowAccessor : r) {
final SQLRowValues rowValues = sqlRowAccessor.createEmptyUpdateRow();
rowValues.put(field.getName(), decimalToFieldType(v));
processBeforeUpdate(sqlRowAccessor, rowValues);
rowValues.update();
 
if (batchfield.getForeignLinkRow() != null) {
 
final List<SQLRow> referentRow = batchfield.getReferentRows(sqlRowAccessor);
for (SQLRow sqlRowT : referentRow) {
SQLRowValues rowValues = sqlRowT.createEmptyUpdateRow();
rowValues.put(batchfield.getField().getName(), decimalToFieldType(v));
processBeforeUpdate(sqlRowT, rowValues);
rowValues.update();
}
} else {
final SQLRowValues rowValues = sqlRowAccessor.createEmptyUpdateRow();
rowValues.put(batchfield.getField().getName(), decimalToFieldType(v));
processBeforeUpdate(sqlRowAccessor, rowValues);
rowValues.update();
}
}
} else if (bAdd.isSelected()) {
 
127,16 → 139,42
BigDecimal v = new BigDecimal(t);
 
for (SQLRowAccessor sqlRowAccessor : r) {
final SQLRowValues rowValues = sqlRowAccessor.createEmptyUpdateRow();
final BigDecimal value = sqlRowAccessor.asRow().getBigDecimal(field.getName());
if (value != null) {
if (isPercent) {
rowValues.put(field.getName(), decimalToFieldType(value.multiply(v.divide(new BigDecimal(100)).add(BigDecimal.ONE))));
} else {
rowValues.put(field.getName(), decimalToFieldType(value.add(v)));
 
if (batchfield.getForeignLinkRow() != null) {
 
final List<SQLRow> referentRow = batchfield.getReferentRows(sqlRowAccessor);
for (SQLRow sqlRowT : referentRow) {
 
SQLRowValues rowValues = sqlRowT.createEmptyUpdateRow();
BigDecimal value = sqlRowT.asRow().getBigDecimal(batchfield.getField().getName());
 
if (value != null) {
if (isPercent) {
rowValues.put(batchfield.getField().getName(), decimalToFieldType(value.multiply(v.divide(new BigDecimal(100)).add(BigDecimal.ONE))));
} else {
rowValues.put(batchfield.getField().getName(), decimalToFieldType(value.add(v)));
}
processBeforeUpdate(sqlRowT, rowValues);
rowValues.update();
}
}
processBeforeUpdate(sqlRowAccessor, rowValues);
rowValues.update();
} else {
 
final SQLRowValues rowValues;
final BigDecimal value;
 
rowValues = sqlRowAccessor.createEmptyUpdateRow();
value = sqlRowAccessor.asRow().getBigDecimal(batchfield.getField().getName());
 
if (value != null) {
if (isPercent) {
rowValues.put(batchfield.getField().getName(), decimalToFieldType(value.multiply(v.divide(new BigDecimal(100)).add(BigDecimal.ONE))));
} else {
rowValues.put(batchfield.getField().getName(), decimalToFieldType(value.add(v)));
}
processBeforeUpdate(sqlRowAccessor, rowValues);
rowValues.update();
}
}
}
} else if (bRemove.isSelected()) {
149,17 → 187,38
 
BigDecimal v = new BigDecimal(t);
for (SQLRowAccessor sqlRowAccessor : r) {
final SQLRowValues rowValues = sqlRowAccessor.createEmptyUpdateRow();
if (batchfield.getForeignLinkRow() != null) {
final List<SQLRow> referentRow = batchfield.getReferentRows(sqlRowAccessor);
if (referentRow != null && !referentRow.isEmpty()) {
for (SQLRow sqlRowT : referentRow) {
 
final BigDecimal value = sqlRowAccessor.asRow().getBigDecimal(field.getName());
if (value != null) {
if (isPercent) {
rowValues.put(field.getName(), decimalToFieldType(value.multiply(v.divide(new BigDecimal(-100)).add(BigDecimal.ONE))));
} else {
rowValues.put(field.getName(), decimalToFieldType(value.add(v)));
SQLRowValues rowValues = sqlRowT.createEmptyUpdateRow();
final BigDecimal value = sqlRowT.getBigDecimal(batchfield.getField().getName());
if (value != null) {
if (isPercent) {
rowValues.put(batchfield.getField().getName(), decimalToFieldType(value.multiply(v.divide(new BigDecimal(-100)).add(BigDecimal.ONE))));
} else {
rowValues.put(batchfield.getField().getName(), decimalToFieldType(value.add(v)));
}
processBeforeUpdate(sqlRowT, rowValues);
rowValues.update();
}
}
}
processBeforeUpdate(sqlRowAccessor, rowValues);
rowValues.update();
} else {
 
SQLRowValues rowValues = sqlRowAccessor.createEmptyUpdateRow();
final BigDecimal value = sqlRowAccessor.asRow().getBigDecimal(batchfield.getField().getName());
 
if (value != null) {
if (isPercent) {
rowValues.put(batchfield.getField().getName(), decimalToFieldType(value.multiply(v.divide(new BigDecimal(-100)).add(BigDecimal.ONE))));
} else {
rowValues.put(batchfield.getField().getName(), decimalToFieldType(value.add(v)));
}
processBeforeUpdate(sqlRowAccessor, rowValues);
rowValues.update();
}
}
}
}
166,7 → 225,7
}
 
private Object decimalToFieldType(BigDecimal v) {
final Class<?> javaType = field.getType().getJavaType();
final Class<?> javaType = batchfield.getField().getType().getJavaType();
if (javaType.equals(BigDecimal.class)) {
return v;
} else if (javaType.equals(Float.class)) {
/trunk/Modules/Module Batch Processing/src/org/openconcerto/modules/common/batchprocessing/ReferenceProcessor.java
18,18 → 18,18
 
public class ReferenceProcessor extends JPanel implements BatchProcessor {
 
private final SQLField field;
private final BatchField field;
final SQLElement element;
private ElementComboBox combo;
 
public ReferenceProcessor(SQLField field) {
public ReferenceProcessor(BatchField field) {
this.field = field;
this.element = ComptaPropsConfiguration.getInstanceCompta().getDirectory().getElement(field.getForeignTable());
this.element = ComptaPropsConfiguration.getInstanceCompta().getDirectory().getElement(field.getField().getForeignTable());
 
if (element != null) {
this.setLayout(new BorderLayout());
this.add(new JLabel("remplacer par "), BorderLayout.WEST);
combo = new ElementComboBox(true, 200);
combo = new ElementComboBox(true, 10);
combo.setMinimal();
combo.setAddIconVisible(false);
combo.init(element);
36,7 → 36,7
this.add(combo, BorderLayout.CENTER);
} else {
this.setLayout(new FlowLayout());
this.add(new JLabelWarning("No element for table " + field.getTable().getName()));
this.add(new JLabelWarning("No element for table " + field.getField().getTable().getName()));
}
}
 
45,7 → 45,7
 
for (SQLRowAccessor sqlRowAccessor : r) {
final SQLRowValues rowValues = sqlRowAccessor.createEmptyUpdateRow();
rowValues.put(field.getName(), combo.getSelectedId());
rowValues.put(field.getField().getName(), combo.getSelectedId());
processBeforeUpdate(sqlRowAccessor, rowValues);
rowValues.update();
}
/trunk/Modules/Module Batch Processing/src/org/openconcerto/modules/common/batchprocessing/product/PurchaseProcessor.java
2,14 → 2,14
 
import java.math.BigDecimal;
 
import org.openconcerto.modules.common.batchprocessing.BatchField;
import org.openconcerto.modules.common.batchprocessing.NumberProcessor;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
 
public class PurchaseProcessor extends NumberProcessor {
 
public PurchaseProcessor(SQLField field) {
public PurchaseProcessor(BatchField field) {
super(field);
}
 
/trunk/Modules/Module Batch Processing/src/org/openconcerto/modules/common/batchprocessing/product/TTCProcessor.java
4,8 → 4,8
 
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
import org.openconcerto.erp.utils.ConvertDevise;
import org.openconcerto.modules.common.batchprocessing.BatchField;
import org.openconcerto.modules.common.batchprocessing.NumberProcessor;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
12,7 → 12,7
 
public class TTCProcessor extends NumberProcessor {
 
public TTCProcessor(SQLField field) {
public TTCProcessor(BatchField field) {
super(field);
}
 
/trunk/Modules/Module Batch Processing/src/org/openconcerto/modules/common/batchprocessing/product/TVAProcessor.java
4,8 → 4,8
 
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
import org.openconcerto.erp.utils.ConvertDevise;
import org.openconcerto.modules.common.batchprocessing.BatchField;
import org.openconcerto.modules.common.batchprocessing.ReferenceProcessor;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
12,7 → 12,7
 
public class TVAProcessor extends ReferenceProcessor {
 
public TVAProcessor(SQLField field) {
public TVAProcessor(BatchField field) {
super(field);
}
 
/trunk/Modules/Module Batch Processing/src/org/openconcerto/modules/common/batchprocessing/product/HTProcessor.java
4,8 → 4,8
 
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
import org.openconcerto.erp.utils.ConvertDevise;
import org.openconcerto.modules.common.batchprocessing.BatchField;
import org.openconcerto.modules.common.batchprocessing.NumberProcessor;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
12,7 → 12,7
 
public class HTProcessor extends NumberProcessor {
 
public HTProcessor(SQLField field) {
public HTProcessor(BatchField field) {
super(field);
}
 
/trunk/Modules/Module Label/.settings/org.eclipse.jdt.core.prefs
New file
0,0 → 1,7
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.8
/trunk/Modules/Module Label/.classpath
1,7 → 1,7
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
<classpathentry combineaccessrules="false" kind="src" path="/OpenConcerto"/>
<classpathentry kind="output" path="bin"/>
</classpath>
/trunk/Modules/Module Label/lib/barcode4j-2.1.0.jar
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
/trunk/Modules/Module Label/lib/barcode4j-2.1.0.jar
New file
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/trunk/Modules/Module Label/lib/jbarcode-0.2.8.jar
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
/trunk/Modules/Module Label/lib/jbarcode-0.2.8.jar
New file
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/LabelPanel.java
15,11 → 15,9
 
import javax.swing.JPanel;
 
import org.openconcerto.sql.model.SQLRowAccessor;
 
public class LabelPanel extends JPanel implements Printable {
 
private List<? extends SQLRowAccessor> list;
private List<? extends Label> list;
private int lines;
private int columns;
private Boolean[][] mask;
29,7 → 27,7
private int topMargin;
private int leftMargin;
 
public LabelPanel(List<? extends SQLRowAccessor> list, int l, int c, LabelRenderer labelRenderer) {
public LabelPanel(List<? extends Label> list, int l, int c, LabelRenderer labelRenderer) {
this.list = list;
this.renderer = labelRenderer;
setSizeLayoutSize(l, c);
48,6 → 46,11
});
}
 
public void setList(List<? extends Label> list) {
this.list = list;
repaint();
}
 
private void setSizeLayoutSize(int l, int c) {
this.lines = l;
this.columns = c;
102,7 → 105,7
g.drawRect(x, y, w, h);
// Label
if (rowIndex < list.size()) {
SQLRowAccessor row = list.get(rowIndex);
Label row = list.get(rowIndex);
renderer.paintLabel(g, row, x, y, w, h, 10f);
}
rowIndex++;
169,7 → 172,7
for (int j = 0; j < this.columns; j++) {
boolean mask = this.mask[i][j];
if (!mask && rowIndex < list.size()) {
SQLRowAccessor row = list.get(rowIndex);
Label row = list.get(rowIndex);
renderer.paintLabel(g, row, j * w + imageableX, i * h + imageableY, w, h, 10f);
}
rowIndex++;
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/96.png
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/96.png
New file
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/logo.png
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/logo.png
New file
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/GS1Frame.java
New file
0,0 → 1,1049
package org.openconcerto.modules.label;
 
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
 
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.SimpleDoc;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JSeparator;
import javax.swing.JSpinner;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.AbstractDocument;
import javax.swing.text.PlainDocument;
 
import org.openconcerto.modules.label.filter.BatchDocumentFilter;
import org.openconcerto.modules.label.filter.EANDocumentFilter;
import org.openconcerto.modules.label.filter.LimitDocumentFilter;
import org.openconcerto.modules.label.filter.NumberOfProductDocumentFilter;
import org.openconcerto.modules.label.gs1.GS1AIElements;
import org.openconcerto.modules.label.gs1.GS1Util;
import org.openconcerto.ui.JDate;
 
import uk.org.okapibarcode.backend.Code128;
import uk.org.okapibarcode.backend.DataMatrix;
import uk.org.okapibarcode.backend.DataMatrix.ForceMode;
import uk.org.okapibarcode.backend.Ean;
import uk.org.okapibarcode.backend.Symbol;
import uk.org.okapibarcode.output.Java2DRenderer;
 
public class GS1Frame extends JFrame {
 
private final SimpleDateFormat dfDate = new SimpleDateFormat("yyMMdd");
private final JTextField textSupplier = new JTextField(20);
private final JTextField textName = new JTextField(20);
private final JTextField textEAN = new JTextField(14);
private final JTextField textBatch = new JTextField(20);
private final JSpinner portZPL = new JSpinner(new SpinnerNumberModel(9100, 24, 10000, 1));
private final JLabel labelEan = new JLabel("EAN 13/14", SwingConstants.RIGHT);
private final JTextField textNumberOfProducts = new JTextField(12);
private final JSpinner labelsSpinner = new JSpinner(new SpinnerNumberModel(5, 0, 9000, 1));
private final JTextField labelBarCode = new JTextField(64);
private final JDate dateDLUODLC = new JDate();
private final JRadioButton b1 = new JRadioButton("DDM/DLUO");
private final JCheckBox checkIgnoreMargins = new JCheckBox("Ignorer les marges de l'imprimante");
private final JRadioButton twoPerPage = new JRadioButton("2");
private final JRadioButton fourPerPage = new JRadioButton("4");
private final JRadioButton radioZPLUSB = new JRadioButton("imprimante locale");
private final JTextField textIP = new JTextField(20);
private final JTabbedPane tabs = new JTabbedPane();
private LabelPanel labelPanel;
private BufferedImage barcodeImage = null;
private BufferedImage barcodeImageBatch = null;
private BufferedImage barcodeDatamatrix = null;
private final Properties properties = new Properties();
 
public GS1Frame() {
super("Code à barres GS1-128");
 
final File file = new File("openconcerto-gs1.properties");
if (file.exists()) {
try {
properties.load(new FileInputStream(file));
} catch (IOException e) {
e.printStackTrace();
}
}
 
final JSplitPane split = new JSplitPane();
final JPanel left = createLeftContent();
final JComponent right = createRightContent();
split.setLeftComponent(left);
split.setRightComponent(right);
this.setContentPane(split);
split.setEnabled(false);
try {
updateList();
} catch (Exception e) {
e.printStackTrace();
}
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
try {
saveProperties();
} catch (IOException e1) {
e1.printStackTrace();
}
dispose();
}
});
}
 
public void saveProperties() throws FileNotFoundException, IOException {
properties.setProperty("supplier", this.textSupplier.getText());
properties.setProperty("product", this.textName.getText());
properties.setProperty("ean", this.textEAN.getText());
properties.setProperty("nbOfProdcuts", this.textNumberOfProducts.getText());
properties.setProperty("batch", this.textBatch.getText());
final Date value = this.dateDLUODLC.getValue();
if (value != null) {
properties.setProperty("sellByDate", String.valueOf(value.getTime()));
} else {
properties.setProperty("sellByDate", "");
}
properties.setProperty("sellBy", b1.isSelected() ? "true" : "false");
properties.setProperty("nbLabels", this.labelsSpinner.getValue().toString());
properties.setProperty("labelsPerPage", fourPerPage.isSelected() ? "4" : "2");
properties.setProperty("ignoreMargin", checkIgnoreMargins.isSelected() ? "true" : "false");
properties.setProperty("usbPrinter", this.radioZPLUSB.isSelected() ? "true" : "false");
properties.setProperty("zplIP", this.textIP.getText());
properties.setProperty("zplPort", this.portZPL.getValue().toString());
properties.setProperty("tab", String.valueOf(tabs.getSelectedIndex()));
 
final FileOutputStream out = new FileOutputStream("openconcerto-gs1.properties");
properties.store(out, "");
out.flush();
out.close();
}
 
boolean isEANValid() {
final String ean = this.textEAN.getText().trim();
if (ean.length() < 13) {
return false;
}
final char cd1 = Ean.calcDigit(ean.substring(0, ean.length() - 1));
final char cd2 = ean.charAt(ean.length() - 1);
return (cd1 == cd2);
}
 
private void updateList() throws Exception {
this.barcodeImage = null;
this.barcodeImageBatch = null;
this.barcodeDatamatrix = null;
this.labelPanel.setList(new ArrayList<>());
this.labelBarCode.setText("");
// Check EAN
String ean = this.textEAN.getText().trim();
if (!isEANValid()) {
this.labelEan.setForeground(Color.RED);
} else {
this.labelEan.setForeground(Color.BLACK);
}
if (ean.length() == 13) {
this.labelEan.setText("EAN 13");
} else if (ean.length() == 14) {
this.labelEan.setText("EAN 14");
} else {
this.labelEan.setText("EAN invalide");
this.labelEan.setForeground(Color.RED);
}
 
if (!isEANValid()) {
return;
}
 
int n = ((Number) this.labelsSpinner.getValue()).intValue();
this.labelBarCode.setText(this.getGS1().formatHumanReadable());
this.labelBarCode.setEditable(false);
GS1Label l = new GS1Label(this.textSupplier.getText(), this.textName.getText(), this.getGS1());
List<GS1Label> list = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
list.add(l);
}
this.labelPanel.setList(list);
 
// Configure the barcode generator
// adjust barcode width here
// 32mm de hatu minimum
// 0,495mm et 1,016mm pour largeur de barre
 
GS1Util util = new GS1Util();
 
{
final GS1AIElements gs128 = getGS128();
Code128 dataMatrix = new Code128();
dataMatrix.setDataType(Symbol.DataType.GS1);
dataMatrix.setBarHeight(70);
dataMatrix.setContent(util.formatDataMatrix(gs128));
int magnification = 5;
int borderSize = 3;
this.barcodeImage = new BufferedImage((dataMatrix.getWidth() * magnification) + (2 * borderSize), (dataMatrix.getHeight() * magnification) + (2 * borderSize), BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = this.barcodeImage.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, (dataMatrix.getWidth() * magnification) + (2 * borderSize), (dataMatrix.getHeight() * magnification) + (2 * borderSize));
Java2DRenderer renderer = new Java2DRenderer(g2d, magnification, Color.WHITE, Color.BLACK);
renderer.render(dataMatrix);
}
final GS1AIElements gs128b = getGS128Batch();
if (!gs128b.isEmpty()) {
Code128 dataMatrix = new Code128();
dataMatrix.setDataType(Symbol.DataType.GS1);
dataMatrix.setBarHeight(90);
dataMatrix.setContent(util.formatDataMatrix(gs128b));
int magnification = 4;
int borderSize = 3;
this.barcodeImageBatch = new BufferedImage((dataMatrix.getWidth() * magnification) + (2 * borderSize), (int) (dataMatrix.getHeight() * magnification) + (2 * borderSize),
BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = this.barcodeImageBatch.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, (dataMatrix.getWidth() * magnification) + (2 * borderSize), (dataMatrix.getHeight() * magnification) + (2 * borderSize));
Java2DRenderer renderer = new Java2DRenderer(g2d, magnification, Color.WHITE, Color.BLACK);
renderer.render(dataMatrix);
}
 
{
String s = util.formatDataMatrix(getGS1());
DataMatrix dataMatrix = new DataMatrix();
dataMatrix.setDataType(Symbol.DataType.GS1);
dataMatrix.setForceMode(ForceMode.SQUARE);
dataMatrix.setContent(s);
int magnification = 30;
int borderSize = 3;
this.barcodeDatamatrix = new BufferedImage((dataMatrix.getWidth() * magnification) + (2 * borderSize), (dataMatrix.getHeight() * magnification) + (2 * borderSize),
BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = this.barcodeDatamatrix.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, (dataMatrix.getWidth() * magnification) + (2 * borderSize), (dataMatrix.getHeight() * magnification) + (2 * borderSize));
Java2DRenderer renderer = new Java2DRenderer(g2d, magnification, Color.WHITE, Color.BLACK);
renderer.render(dataMatrix);
}
 
// ImageIO.write(barcodeImage, "PNG", new File("barcode.png"));
// ImageIO.write(barcodeImageBatch, "PNG", new File("barcode2.png"));
// ImageIO.write(barcodeDatamatrix, "PNG", new File("datamatrix.png"));
 
}
 
private JPanel createLeftContent() {
final JPanel p = new JPanel();
p.setLayout(new GridBagLayout());
final GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.gridy = 0;
c.gridx = 0;
c.gridwidth = 3;
p.add(createLogo(), c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = 1;
c.gridy++;
c.anchor = GridBagConstraints.WEST;
c.insets = new Insets(2, 3, 2, 2);
//
c.weightx = 0;
c.gridwidth = 1;
p.add(new JLabel("Fournisseur / fabricant", SwingConstants.RIGHT), c);
c.gridx++;
c.weightx = 1;
c.gridwidth = 2;
this.textSupplier.setText(properties.getProperty("supplier", ""));
((AbstractDocument) this.textSupplier.getDocument()).setDocumentFilter(new LimitDocumentFilter(22));
p.add(this.textSupplier, c);
 
//
c.gridx = 0;
c.gridy++;
c.weightx = 0;
c.gridwidth = 1;
p.add(new JLabel("Désignation du produit", SwingConstants.RIGHT), c);
c.gridx++;
c.weightx = 1;
c.gridwidth = 2;
this.textName.setText(properties.getProperty("product", "Biscuit Extra"));
((AbstractDocument) this.textName.getDocument()).setDocumentFilter(new LimitDocumentFilter(22));
p.add(this.textName, c);
 
// EAN 13/14
c.gridx = 0;
c.gridy++;
c.weightx = 0;
c.gridwidth = 1;
p.add(this.labelEan, c);
c.gridx++;
c.weightx = 1;
c.gridwidth = 2;
this.textEAN.setText(properties.getProperty("ean", "7612345678900"));
((AbstractDocument) this.textEAN.getDocument()).setDocumentFilter(new EANDocumentFilter());
p.add(this.textEAN, c);
// nb de produit
c.gridx = 0;
c.gridy++;
c.weightx = 0;
c.gridwidth = 1;
p.add(new JLabel("Nombre par carton", SwingConstants.RIGHT), c);
c.gridx++;
c.weightx = 1;
c.gridwidth = 2;
c.fill = GridBagConstraints.NONE;
PlainDocument doc = (PlainDocument) this.textNumberOfProducts.getDocument();
doc.setDocumentFilter(new NumberOfProductDocumentFilter());
this.textNumberOfProducts.setText(properties.getProperty("nbOfProdcuts", "10"));
p.add(this.textNumberOfProducts, c);
// Numéro de lot
c.gridx = 0;
c.gridy++;
c.weightx = 0;
c.gridwidth = 1;
c.fill = GridBagConstraints.HORIZONTAL;
p.add(new JLabel("Lot", SwingConstants.RIGHT), c);
c.gridx++;
c.weightx = 1;
c.gridwidth = 2;
((AbstractDocument) this.textBatch.getDocument()).setDocumentFilter(new BatchDocumentFilter());
this.textBatch.setText(properties.getProperty("batch", ""));
p.add(this.textBatch, c);
// DLC
c.gridx = 1;
c.gridy++;
c.weightx = 0;
c.gridwidth = 1;
 
p.add(this.b1, c);
c.gridx++;
c.weightx = 1;
this.dateDLUODLC.setFormat(new SimpleDateFormat("dd/MM/yyyy"));
if (!properties.getProperty("sellByDate", "").isEmpty()) {
this.dateDLUODLC.setDateInMillis(Long.parseLong(properties.getProperty("sellByDate")));
}
p.add(this.dateDLUODLC, c);
// DLUO
c.gridx = 1;
c.gridy++;
c.weightx = 0;
JRadioButton b2 = new JRadioButton("DLC");
p.add(b2, c);
c.gridx++;
c.weightx = 1;
 
this.b1.setSelected(properties.getProperty("sellBy", "true").equals("true"));
b2.setSelected(!properties.getProperty("sellBy", "true").equals("true"));
// Barcode
c.gridx = 0;
c.gridy++;
c.weightx = 0;
c.gridwidth = 3;
p.add(new JLabel("Code GS1 complet de l'étiquette", SwingConstants.LEFT), c);
c.gridy++;
c.weightx = 1;
this.labelBarCode.setFont(this.textBatch.getFont());
this.labelBarCode.setEnabled(false);
p.add(this.labelBarCode, c);
 
// Nombre d'étiquettes
c.gridx = 0;
c.gridy++;
c.weightx = 0;
c.gridwidth = 1;
p.add(new JLabel("Nombre d'étiquettes", SwingConstants.RIGHT), c);
c.gridx++;
c.weightx = 0;
c.fill = GridBagConstraints.NONE;
 
this.labelsSpinner.setValue(Integer.parseInt(properties.getProperty("nbLabels", "4")));
 
p.add(this.labelsSpinner, c);
 
final JPanel spacer = new JPanel();
spacer.setOpaque(false);
c.gridy++;
c.weighty = 1;
p.add(spacer, c);
 
final ButtonGroup gr = new ButtonGroup();
gr.add(this.b1);
gr.add(b2);
 
// Listeners
 
final ChangeListener changeListener = new ChangeListener() {
 
@Override
public void stateChanged(ChangeEvent e) {
try {
updateList();
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
this.labelsSpinner.addChangeListener(changeListener);
 
final DocumentListener dListener = new DocumentListener() {
 
@Override
public void removeUpdate(DocumentEvent e) {
changedUpdate(e);
}
 
@Override
public void insertUpdate(DocumentEvent e) {
changedUpdate(e);
 
}
 
@Override
public void changedUpdate(DocumentEvent e) {
try {
updateList();
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
this.textSupplier.getDocument().addDocumentListener(dListener);
this.textName.getDocument().addDocumentListener(dListener);
this.textEAN.getDocument().addDocumentListener(dListener);
this.textNumberOfProducts.getDocument().addDocumentListener(dListener);
this.textBatch.getDocument().addDocumentListener(dListener);
 
this.dateDLUODLC.addValueListener(new PropertyChangeListener() {
 
@Override
public void propertyChange(PropertyChangeEvent evt) {
try {
updateList();
} catch (Exception e) {
e.printStackTrace();
}
 
}
});
this.b1.addChangeListener(changeListener);
b2.addChangeListener(changeListener);
return p;
}
 
private Component createLogo() {
final Image i1 = new ImageIcon(this.getClass().getResource("logo.png")).getImage();
final Image i2 = new ImageIcon(this.getClass().getResource("oc-qrcode.png")).getImage();
return new JComponent() {
@Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
g.drawImage(i1, 0, 3, null);
g.drawImage(i2, getWidth() - i2.getWidth(null), 0, null);
g.setColor(Color.GRAY);
g.drawLine(0, 58, getWidth(), 58);
}
 
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 59);
}
};
}
 
private JComponent createRightContent() {
 
final JPanel panelA4 = new JPanel();
panelA4.setOpaque(false);
panelA4.setLayout(new GridBagLayout());
final GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(2, 3, 2, 2);
c.gridx = 0;
c.gridy = 0;
panelA4.add(createToolBar(), c);
c.gridy++;
// panelA4.add(createToolBar2(), c);
// c.gridy++;
c.insets = new Insets(0, 0, 0, 0);
panelA4.add(new JSeparator(JSeparator.HORIZONTAL), c);
c.gridy++;
c.weightx = 1;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
final int columnCount = fourPerPage.isSelected() ? 2 : 1;
this.labelPanel = new LabelPanel(new ArrayList<Label>(), 2, columnCount, createRenderer()) {
@Override
public Dimension getPreferredSize() {
return new Dimension(190 * 3, 280 * 3);
}
};
this.labelPanel.setIgnoreMargins(checkIgnoreMargins.isSelected());
panelA4.add(this.labelPanel, c);
tabs.addTab("Feuilles A4", panelA4);
tabs.addTab("Imprimante ZPL", createZPLPanel());
tabs.setSelectedIndex(Integer.parseInt(properties.getProperty("tab", "0")));
return tabs;
}
 
private Component createZPLPanel() {
final JPanel panelZPL = new JPanel();
panelZPL.setOpaque(false);
panelZPL.setLayout(new GridBagLayout());
final GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(2, 3, 2, 2);
c.gridx = 0;
c.gridy = 0;
c.weightx = 0;
c.gridwidth = 1;
c.anchor = GridBagConstraints.EAST;
 
radioZPLUSB.setOpaque(false);
panelZPL.add(radioZPLUSB, c);
c.gridx += 5;
c.weightx = 1;
c.fill = GridBagConstraints.NONE;
c.insets = new Insets(4, 3, 2, 4);
final JButton buttonPrintZPL = new JButton("Imprimer");
buttonPrintZPL.setOpaque(false);
panelZPL.add(buttonPrintZPL, c);
c.insets = new Insets(2, 3, 2, 2);
c.gridx = 0;
c.gridy++;
c.weightx = 0;
c.fill = GridBagConstraints.HORIZONTAL;
final JRadioButton radioZPLNetwork = new JRadioButton("imprimante réseau");
radioZPLNetwork.setOpaque(false);
panelZPL.add(radioZPLNetwork, c);
c.gridx++;
panelZPL.add(new JLabel("Adresse"), c);
c.gridx++;
 
textIP.setText(properties.getProperty("zplIP", "192.168.1.50"));
panelZPL.add(textIP, c);
c.gridx++;
panelZPL.add(new JLabel("Port"), c);
this.portZPL.setValue(Integer.parseInt(properties.getProperty("zplPort", "9100")));
c.gridx++;
panelZPL.add(this.portZPL, c);
c.gridx = 0;
c.gridy++;
c.gridwidth = 6;
 
radioZPLUSB.setSelected(properties.getProperty("usbPrinter", "true").equals("true"));
radioZPLNetwork.setSelected(!properties.getProperty("usbPrinter", "true").equals("true"));
 
final ButtonGroup g = new ButtonGroup();
g.add(radioZPLUSB);
g.add(radioZPLNetwork);
 
c.anchor = GridBagConstraints.NORTHWEST;
panelZPL.add(new JLabel("L'impression nécessite une imprimante d'étiquettes compatible ZPL (Zebra ou autre)."), c);
c.gridy++;
c.weighty = 1;
panelZPL.add(new JLabel("Vous pouvez paramétrer l'impression par défaut (largeur 6\" à 203 dpi) dans le fichier zpl.txt ."), c);
buttonPrintZPL.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
if (!isEANValid()) {
JOptionPane.showMessageDialog(GS1Frame.this, "EAN invalide");
return;
}
 
final String code = createZPLCode();
System.out.println("ZPL:");
System.out.println(code);
byte[] data = code.getBytes(StandardCharsets.US_ASCII);
if (radioZPLNetwork.isSelected()) {
Socket socket = null;
try {
socket = new Socket(textIP.getText(), ((Number) GS1Frame.this.portZPL.getValue()).intValue());
final DataOutputStream out = new DataOutputStream(socket.getOutputStream());
final int nb = ((Number) labelsSpinner.getValue()).intValue();
for (int i = 0; i < nb; i++) {
out.write(data);
}
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(buttonPrintZPL, "Erreur d'impression réseau : " + ex.getMessage());
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
 
}
} else {
try {
final PrinterJob pj1 = PrinterJob.getPrinterJob();
if (pj1.printDialog()) {
final PrintService ps = pj1.getPrintService();
final DocPrintJob pj = ps.createPrintJob();
final SimpleDoc doc = new SimpleDoc(data, DocFlavor.BYTE_ARRAY.AUTOSENSE, null);
final int nb = ((Number) labelsSpinner.getValue()).intValue();
for (int i = 0; i < nb; i++) {
pj.print(doc, null);
}
}
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(buttonPrintZPL, "Erreur d'impression locale : " + ex.getMessage());
}
}
}
 
});
 
return panelZPL;
 
}
 
private LabelRenderer createRenderer() {
return new LabelRenderer() {
 
@Override
public void paintLabel(Graphics g, Label label, int x, int y, int gridWith, int gridHeight, float fontSize) {
final Graphics2D g2d = (Graphics2D) g;
g.setColor(Color.BLACK);
g2d.setStroke(new BasicStroke(3));
String str1 = GS1Frame.this.textSupplier.getText().trim();
String str2 = GS1Frame.this.textName.getText();
int pos1 = 26;
if (str1.isEmpty()) {
str1 = GS1Frame.this.textName.getText();
str2 = "";
pos1 += 16;
}
 
final AffineTransform defaultAt = g2d.getTransform();
final AffineTransform at = ((AffineTransform) (g2d.getTransform().clone()));
at.rotate(-Math.PI / 2);
g2d.setTransform(at);
g.setFont(getFont().deriveFont(15f));
final int d1 = 60;
 
final int d2 = 60;
g.drawString(str1, -y - gridHeight + d1, x + pos1);
g.drawString(str2, -y - gridHeight + d2, x + 58);
if (GS1Frame.this.barcodeDatamatrix != null) {
float ratioDatamatrix = 15f;
final int wd = (int) (GS1Frame.this.barcodeDatamatrix.getWidth() / ratioDatamatrix);
final int hd = (int) (GS1Frame.this.barcodeDatamatrix.getHeight() / ratioDatamatrix);
g.drawImage(GS1Frame.this.barcodeDatamatrix, -y - 10 - wd, x + 10, wd, hd, null);
final int w1 = GS1Frame.this.barcodeImage.getWidth() / 4;
final int h1 = GS1Frame.this.barcodeImage.getHeight() / 4;
g.drawImage(GS1Frame.this.barcodeImage, -y + -gridHeight + 60, x + 70, w1, h1, null);
 
}
if (GS1Frame.this.barcodeImageBatch != null) {
// GS1-128 numero de lot
final int w2 = GS1Frame.this.barcodeImageBatch.getWidth() / 4;
final int h2 = GS1Frame.this.barcodeImageBatch.getHeight() / 4;
g.drawImage(GS1Frame.this.barcodeImageBatch, -y - gridHeight + 60, x + 180, w2, h2, null);
}
g2d.setTransform(defaultAt);
 
}
};
 
}
 
public JPanel createToolBar() {
final JPanel toolbar = new JPanel();
toolbar.setOpaque(false);
toolbar.setLayout(new GridBagLayout());
final GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(2, 3, 2, 2);
c.gridx = 0;
c.gridy = 0;
c.weightx = 0;
c.gridwidth = 1;
toolbar.add(new JLabel("Etiquettes par page"), c);
c.gridx++;
 
twoPerPage.setOpaque(false);
fourPerPage.setOpaque(false);
final ButtonGroup g = new ButtonGroup();
g.add(twoPerPage);
g.add(fourPerPage);
 
if (properties.getProperty("labelsPerPage", "4").equals("4")) {
fourPerPage.setSelected(true);
} else {
twoPerPage.setSelected(true);
}
 
toolbar.add(twoPerPage, c);
c.gridx++;
toolbar.add(fourPerPage, c);
c.gridx++;
checkIgnoreMargins.setOpaque(false);
checkIgnoreMargins.setSelected(properties.getProperty("ignoreMargin", "false").equals("true"));
c.gridx++;
toolbar.add(checkIgnoreMargins, c);
c.gridx++;
c.weightx = 1;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.NORTHEAST;
final JButton printButton = new JButton("Imprimer");
printButton.setOpaque(false);
toolbar.add(printButton, c);
c.gridx++;
 
twoPerPage.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
if (twoPerPage.isSelected()) {
GS1Frame.this.labelPanel.setColumnCount(1);
} else {
GS1Frame.this.labelPanel.setColumnCount(2);
}
 
}
});
 
fourPerPage.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
if (twoPerPage.isSelected()) {
GS1Frame.this.labelPanel.setColumnCount(1);
} else {
GS1Frame.this.labelPanel.setColumnCount(2);
}
 
}
});
 
printButton.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
if (!isEANValid()) {
JOptionPane.showMessageDialog(GS1Frame.this, "EAN invalide");
return;
}
 
final PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(GS1Frame.this.labelPanel);
boolean ok = job.printDialog();
if (ok) {
try {
job.print();
} catch (PrinterException ex) {
JOptionPane.showMessageDialog(GS1Frame.this, "Print error :" + ex.getMessage());
}
}
 
}
});
checkIgnoreMargins.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
GS1Frame.this.labelPanel.setIgnoreMargins(checkIgnoreMargins.isSelected());
 
}
});
return toolbar;
}
 
public JPanel createToolBar2() {
final JPanel toolbar = new JPanel();
toolbar.setOpaque(false);
toolbar.setLayout(new GridBagLayout());
final GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(2, 3, 2, 2);
c.gridx = 0;
c.gridy = 0;
c.weightx = 0;
c.gridwidth = 1;
c.fill = GridBagConstraints.NONE;
toolbar.add(new JLabel("Marge en haut (mm)"), c);
c.gridx++;
final JSpinner sLines = new JSpinner(new SpinnerNumberModel(0, 0, 200, 1));
toolbar.add(sLines, c);
c.gridx++;
toolbar.add(new JLabel("Marge à gauche (mm)"), c);
c.gridx++;
final JSpinner sColums = new JSpinner(new SpinnerNumberModel(0, 0, 200, 1));
c.weightx = 1;
toolbar.add(sColums, c);
c.gridx++;
 
sLines.addChangeListener(new ChangeListener() {
 
@Override
public void stateChanged(ChangeEvent e) {
final Number n = (Number) sLines.getValue();
if (n != null) {
GS1Frame.this.labelPanel.setTopMargin(n.intValue());
}
}
});
sColums.addChangeListener(new ChangeListener() {
 
@Override
public void stateChanged(ChangeEvent e) {
final Number n = (Number) sColums.getValue();
if (n != null) {
GS1Frame.this.labelPanel.setLeftMargin(n.intValue());
}
}
});
 
return toolbar;
}
 
public String readZPLScript() {
if (new File("zpl.txt").exists()) {
try (InputStream in = new FileInputStream(new File("zpl.txt"))) {
return readAscii(in);
} catch (Exception e) {
e.printStackTrace();
}
} else {
try (InputStream in = GS1Frame.class.getResourceAsStream("default-zpl.txt")) {
return readAscii(in);
} catch (Exception e) {
e.printStackTrace();
}
 
}
return "";
}
 
protected String createZPLCode() {
final String script = readZPLScript();
final BufferedReader reader = new BufferedReader(new StringReader(script));
final StringBuilder builder = new StringBuilder();
final GS1Util u = new GS1Util();
try {
String line = reader.readLine();
while (line != null) {
if (line.contains("XXXXXXXXXX")) {
if (!this.textSupplier.getText().isEmpty()) {
line = line.replace("XXXXXXXXXX", this.textSupplier.getText());
builder.append(line);
builder.append("\r\n");
}
} else if (line.contains("YYYYYYYYYY")) {
line = line.replace("YYYYYYYYYY", this.textName.getText());
builder.append(line);
builder.append("\r\n");
} else if (line.contains("(02)7612345678900(15)201218(37)9999")) {
line = line.replace("(02)7612345678900(15)201218(37)9999", getGS128().formatHumanReadable());
builder.append(line);
builder.append("\r\n");
 
} else if (line.contains("(10)LLLLLLLLL")) {
GS1AIElements batch = getGS128Batch();
if (!batch.isEmpty()) {
line = line.replace("(10)LLLLLLLLL", batch.formatHumanReadable());
builder.append(line);
builder.append("\r\n");
}
} else if (line.contains("OPENCONCERTO")) {
GS1AIElements all = getGS1();
line = line.replace("OPENCONCERTO", u.formatZPL(all));
builder.append(line);
builder.append("\r\n");
 
} else {
builder.append(line);
builder.append("\r\n");
}
 
line = reader.readLine();
}
} catch (Exception e) {
e.printStackTrace();
}
 
return builder.toString();
}
 
private GS1AIElements getGS1() {
final GS1AIElements gs1 = new GS1AIElements();
final String ean = this.textEAN.getText().trim();
if (!ean.isEmpty()) {
if (ean.length() == 13 || (ean.length() == 14 && ean.charAt(0) == '0')) {
if (ean.length() == 13) {
gs1.put("02", '0' + ean);
} else {
gs1.put("02", ean);
}
} else {
gs1.put("01", ean);
}
}
 
if (this.dateDLUODLC.getValue() != null) {
String date = this.dfDate.format(this.dateDLUODLC.getValue());
if (this.b1.isSelected()) {
gs1.put("15", date);
} else {
gs1.put("17", date);
}
}
 
final String nbProducts = this.textNumberOfProducts.getText();
if (!nbProducts.trim().isEmpty()) {
int n = Integer.parseInt(this.textNumberOfProducts.getText());
gs1.put("37", String.valueOf(n));
 
}
final String batch = this.textBatch.getText().trim();
if (!batch.isEmpty()) {
gs1.put("10", batch);
}
 
return gs1;
}
 
private GS1AIElements getGS128Batch() {
final GS1AIElements gs1 = new GS1AIElements();
final String batch = this.textBatch.getText().trim();
if (!batch.isEmpty()) {
gs1.put("10", batch);
}
return gs1;
}
 
private GS1AIElements getGS128() {
final GS1AIElements gs1 = getGS1();
gs1.remove("10");
return gs1;
}
 
public String readAscii(final InputStream in) throws IOException {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final byte[] buf = new byte[8192];
int length;
while ((length = in.read(buf)) > 0) {
out.write(buf, 0, length);
}
out.flush();
out.close();
return new String(out.toByteArray(), StandardCharsets.US_ASCII);
}
 
static List<Image> frameIcon;
 
public static synchronized List<Image> getFrameIcon() {
if (frameIcon == null) {
frameIcon = new ArrayList<>();
final int[] sizes = { 16, 32, 48, 96 };
for (int i = 0; i < sizes.length; i++) {
int v = sizes[i];
try {
frameIcon.add(new ImageIcon(GS1Frame.class.getResource(v + ".png")).getImage());
} catch (Exception e) {
e.printStackTrace();
}
}
}
return frameIcon;
}
 
public static void main(String[] args) {
 
if (!new File("zpl.txt").exists()) {
final InputStream in = GS1Frame.class.getResourceAsStream("default-zpl.txt");
try (FileOutputStream fOut = new FileOutputStream(new File("zpl.txt"))) {
byte[] buf = new byte[8192];
int length;
while ((length = in.read(buf)) > 0) {
fOut.write(buf, 0, length);
}
fOut.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
SwingUtilities.invokeLater(new Runnable() {
 
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e1) {
e1.printStackTrace();
}
 
final GS1Frame f = new GS1Frame();
f.setIconImages(getFrameIcon());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
f.setLocationRelativeTo(null);
f.setResizable(false);
 
}
});
 
}
 
}
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/filter/ISO646DocumentFilter.java
New file
0,0 → 1,19
package org.openconcerto.modules.label.filter;
 
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
 
import org.openconcerto.modules.label.ISO646;
 
public class ISO646DocumentFilter extends DocumentFilter {
@Override
public void insertString(FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException {
super.insertString(fb, offset, ISO646.clean(text), attr);
}
 
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
super.replace(fb, offset, length, ISO646.clean(text), attrs);
}
}
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/filter/LimitDocumentFilter.java
New file
0,0 → 1,30
package org.openconcerto.modules.label.filter;
 
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
 
public class LimitDocumentFilter extends DocumentFilter {
 
private int limit;
 
public LimitDocumentFilter(int limit) {
if (limit <= 0) {
throw new IllegalArgumentException("Limit can not be <= 0");
}
this.limit = limit;
}
 
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
int currentLength = fb.getDocument().getLength();
int overLimit = (currentLength + text.length()) - limit - length;
if (overLimit > 0) {
text = text.substring(0, text.length() - overLimit);
}
if (text.length() > 0) {
super.replace(fb, offset, length, text, attrs);
}
}
 
}
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/filter/NumberOfProductDocumentFilter.java
New file
0,0 → 1,47
package org.openconcerto.modules.label.filter;
 
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
 
public class NumberOfProductDocumentFilter extends DocumentFilter {
private boolean isValid(String testText) {
if (testText.length() > 8) {
return false;
}
if (testText.isEmpty()) {
return true;
}
int intValue = 0;
try {
intValue = Integer.parseInt(testText.trim());
} catch (NumberFormatException e) {
return false;
}
if (intValue < 1 || intValue > 99999999) {
return false;
}
return true;
}
 
@Override
public void insertString(FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException {
StringBuilder sb = new StringBuilder();
sb.append(fb.getDocument().getText(0, fb.getDocument().getLength()));
sb.insert(offset, text);
if (isValid(sb.toString())) {
super.insertString(fb, offset, text, attr);
}
}
 
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
StringBuilder sb = new StringBuilder();
sb.append(fb.getDocument().getText(0, fb.getDocument().getLength()));
int end = offset + length;
sb.replace(offset, end, text);
if (isValid(sb.toString())) {
super.replace(fb, offset, length, text, attrs);
}
}
}
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/filter/BatchDocumentFilter.java
New file
0,0 → 1,23
package org.openconcerto.modules.label.filter;
 
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
 
import org.openconcerto.modules.label.ISO646;
 
public class BatchDocumentFilter extends LimitDocumentFilter {
 
public BatchDocumentFilter() {
super(20);
}
 
@Override
public void insertString(FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException {
super.insertString(fb, offset, ISO646.clean(text), attr);
}
 
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
super.replace(fb, offset, length, ISO646.clean(text), attrs);
}
}
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/filter/EANDocumentFilter.java
New file
0,0 → 1,36
package org.openconcerto.modules.label.filter;
 
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
 
public class EANDocumentFilter extends LimitDocumentFilter {
 
public EANDocumentFilter() {
super(14);
}
 
@Override
public void insertString(FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException {
super.insertString(fb, offset, clean(text), attr);
}
 
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
super.replace(fb, offset, length, clean(text), attrs);
}
 
public static String clean(String s) {
final int length = s.length();
final StringBuilder b = new StringBuilder(length);
for (int i = 0; i < length; i++) {
final char charAt = s.charAt(i);
if (Character.isDigit(charAt)) {
b.append(s.charAt(i));
} else {
b.append('0');
}
}
return b.toString();
}
 
}
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/LabelRenderer.java
2,8 → 2,6
 
import java.awt.Graphics;
 
import org.openconcerto.sql.model.SQLRowAccessor;
 
public interface LabelRenderer {
public void paintLabel(Graphics g, SQLRowAccessor row, int x, int y, int gridWith, int gridHeight, float fontSize);
public void paintLabel(Graphics g, Label label, int x, int y, int gridWith, int gridHeight, float fontSize);
}
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/gs1/GS1AIElements.java
New file
0,0 → 1,259
package org.openconcerto.modules.label.gs1;
 
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
 
public class GS1AIElements {
static final HashMap<String, GS1ApplicationIdentifier> GS1_128_AI = new HashMap<>();
static {
GS1_128_AI.put("00", new GS1ApplicationIdentifier(0, 18, false, false));
GS1_128_AI.put("01", new GS1ApplicationIdentifier(0, 14, false, false));
GS1_128_AI.put("02", new GS1ApplicationIdentifier(0, 14, false, false));
GS1_128_AI.put("10", new GS1ApplicationIdentifier(0, 20, true, false));
GS1_128_AI.put("11", new GS1ApplicationIdentifier(0, 6, false, false));
GS1_128_AI.put("12", new GS1ApplicationIdentifier(0, 6, false, false));
GS1_128_AI.put("13", new GS1ApplicationIdentifier(0, 6, false, false));
GS1_128_AI.put("14", new GS1ApplicationIdentifier(0, 6, false, false));
GS1_128_AI.put("15", new GS1ApplicationIdentifier(0, 6, false, false));
GS1_128_AI.put("17", new GS1ApplicationIdentifier(0, 6, false, false));
GS1_128_AI.put("20", new GS1ApplicationIdentifier(0, 2, false, false));
GS1_128_AI.put("21", new GS1ApplicationIdentifier(0, 20, true, false));
GS1_128_AI.put("240", new GS1ApplicationIdentifier(0, 30, true, false));
GS1_128_AI.put("241", new GS1ApplicationIdentifier(0, 30, true, false));
GS1_128_AI.put("242", new GS1ApplicationIdentifier(0, 6, true, false));
GS1_128_AI.put("250", new GS1ApplicationIdentifier(0, 30, true, false));
GS1_128_AI.put("251", new GS1ApplicationIdentifier(0, 30, true, false));
GS1_128_AI.put("253", new GS1ApplicationIdentifier(13, 30, true, false));
GS1_128_AI.put("254", new GS1ApplicationIdentifier(0, 20, true, false));
GS1_128_AI.put("255", new GS1ApplicationIdentifier(13, 25, true, false));
GS1_128_AI.put("30", new GS1ApplicationIdentifier(0, 8, true, false));
GS1_128_AI.put("310", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("311", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("312", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("313", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("314", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("315", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("316", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("320", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("321", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("322", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("323", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("324", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("325", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("326", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("327", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("328", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("329", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("330", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("331", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("332", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("333", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("334", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("335", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("336", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("340", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("341", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("342", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("343", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("344", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("345", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("346", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("347", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("348", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("349", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("350", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("351", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("352", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("353", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("354", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("355", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("356", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("357", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("360", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("361", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("362", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("363", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("364", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("365", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("366", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("367", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("368", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("369", new GS1ApplicationIdentifier(0, 6, false, true));
GS1_128_AI.put("37", new GS1ApplicationIdentifier(0, 8, true, false));
GS1_128_AI.put("390", new GS1ApplicationIdentifier(0, 15, true, true));
GS1_128_AI.put("391", new GS1ApplicationIdentifier(3, 18, true, true));
GS1_128_AI.put("392", new GS1ApplicationIdentifier(0, 15, true, true));
GS1_128_AI.put("393", new GS1ApplicationIdentifier(3, 18, true, true));
GS1_128_AI.put("400", new GS1ApplicationIdentifier(0, 30, true, false));
GS1_128_AI.put("401", new GS1ApplicationIdentifier(0, 30, true, false));
GS1_128_AI.put("402", new GS1ApplicationIdentifier(0, 17, false, false));
GS1_128_AI.put("403", new GS1ApplicationIdentifier(3, 30, true, false));
GS1_128_AI.put("410", new GS1ApplicationIdentifier(0, 17, false, false));
GS1_128_AI.put("411", new GS1ApplicationIdentifier(0, 17, false, false));
GS1_128_AI.put("412", new GS1ApplicationIdentifier(0, 17, false, false));
GS1_128_AI.put("413", new GS1ApplicationIdentifier(0, 17, false, false));
GS1_128_AI.put("414", new GS1ApplicationIdentifier(0, 17, false, false));
GS1_128_AI.put("420", new GS1ApplicationIdentifier(0, 20, true, false));
GS1_128_AI.put("421", new GS1ApplicationIdentifier(0, 0, true, false));
GS1_128_AI.put("422", new GS1ApplicationIdentifier(0, 3, false, false));
GS1_128_AI.put("423", new GS1ApplicationIdentifier(3, 15, true, false));
GS1_128_AI.put("424", new GS1ApplicationIdentifier(0, 3, false, false));
GS1_128_AI.put("425", new GS1ApplicationIdentifier(0, 3, false, false));
GS1_128_AI.put("426", new GS1ApplicationIdentifier(0, 3, false, false));
GS1_128_AI.put("7001", new GS1ApplicationIdentifier(0, 13, false, false));
GS1_128_AI.put("7002", new GS1ApplicationIdentifier(0, 30, false, false));
GS1_128_AI.put("7003", new GS1ApplicationIdentifier(0, 10, false, false));
GS1_128_AI.put("7004", new GS1ApplicationIdentifier(0, 4, true, false));
GS1_128_AI.put("8001", new GS1ApplicationIdentifier(0, 14, false, false));
GS1_128_AI.put("8002", new GS1ApplicationIdentifier(0, 20, true, false));
GS1_128_AI.put("8003", new GS1ApplicationIdentifier(14, 30, true, false));
GS1_128_AI.put("8004", new GS1ApplicationIdentifier(0, 30, true, false));
GS1_128_AI.put("8005", new GS1ApplicationIdentifier(0, 6, false, false));
GS1_128_AI.put("8006", new GS1ApplicationIdentifier(0, 18, false, false));
GS1_128_AI.put("8007", new GS1ApplicationIdentifier(0, 30, true, false));
GS1_128_AI.put("8008", new GS1ApplicationIdentifier(8, 12, true, false));
GS1_128_AI.put("8018", new GS1ApplicationIdentifier(0, 18, false, false));
GS1_128_AI.put("8020", new GS1ApplicationIdentifier(0, 25, true, false));
GS1_128_AI.put("8100", new GS1ApplicationIdentifier(0, 6, false, false));
GS1_128_AI.put("8101", new GS1ApplicationIdentifier(0, 10, false, false));
GS1_128_AI.put("8102", new GS1ApplicationIdentifier(0, 2, false, false));
GS1_128_AI.put("8110", new GS1ApplicationIdentifier(0, 30, true, false));
GS1_128_AI.put("8200", new GS1ApplicationIdentifier(0, 70, true, false));
GS1_128_AI.put("90", new GS1ApplicationIdentifier(0, 30, true, false));
GS1_128_AI.put("91", new GS1ApplicationIdentifier(0, 30, true, false));
GS1_128_AI.put("92", new GS1ApplicationIdentifier(0, 30, true, false));
GS1_128_AI.put("93", new GS1ApplicationIdentifier(0, 30, true, false));
GS1_128_AI.put("94", new GS1ApplicationIdentifier(0, 30, true, false));
GS1_128_AI.put("95", new GS1ApplicationIdentifier(0, 30, true, false));
GS1_128_AI.put("96", new GS1ApplicationIdentifier(0, 30, true, false));
GS1_128_AI.put("97", new GS1ApplicationIdentifier(0, 30, true, false));
GS1_128_AI.put("98", new GS1ApplicationIdentifier(0, 30, true, false));
GS1_128_AI.put("99", new GS1ApplicationIdentifier(0, 30, true, false));
}
 
private final ArrayList<String> keysAndValues = new ArrayList<>();
 
public GS1AIElements() {
 
}
 
public boolean isEmpty() {
return this.keysAndValues.isEmpty();
}
 
public boolean containsKey(String key) {
final int size = this.keysAndValues.size();
for (int i = 0; i < size; i += 2) {
if (this.keysAndValues.get(i).equals(key)) {
return true;
}
}
return false;
}
 
public boolean containsValue(String value) {
final int size = this.keysAndValues.size();
for (int i = 1; i < size; i += 2) {
if (this.keysAndValues.get(i).equals(value)) {
return true;
}
}
return false;
}
 
public String getKey(int index) {
return this.keysAndValues.get(index * 2);
}
 
public String getValue(int index) {
return this.keysAndValues.get(1 + index * 2);
}
 
public String get(String key) {
final int size = this.keysAndValues.size();
for (int i = 0; i < size; i += 2) {
if (this.keysAndValues.get(i).equals(key)) {
 
return this.keysAndValues.get(i + 1);
}
}
return null;
}
 
public String put(String key, String value) {
GS1ApplicationIdentifier ai = GS1_128_AI.get(key);
if (ai == null) {
throw new IllegalArgumentException("AI " + key + " unknown");
}
if (ai.variableLength) {
if (value.length() < ai.minLength) {
throw new IllegalArgumentException("AI " + key + " value length must >= " + ai.minLength + " but is " + value.length() + " for value " + value);
}
if (value.length() > ai.length) {
throw new IllegalArgumentException("AI " + key + " value length must be <= " + ai.length + " but is " + value.length() + " for value " + value);
}
} else {
if (value.length() != ai.length) {
throw new IllegalArgumentException("AI " + key + " value length must be " + ai.length + " but is " + value.length() + " for value " + value);
}
}
 
final int size = this.keysAndValues.size();
for (int i = 0; i < size; i += 2) {
if (this.keysAndValues.get(i).equals(key)) {
final String old = this.keysAndValues.get(i + 1);
this.keysAndValues.set(i + 1, value);
return old;
}
}
this.keysAndValues.add(key);
this.keysAndValues.add(value);
return null;
}
 
public String remove(String key) {
final int size = this.keysAndValues.size();
for (int i = 0; i < size; i += 2) {
if (this.keysAndValues.get(i).equals(key)) {
this.keysAndValues.remove(i);
return this.keysAndValues.remove(i);
}
}
return null;
}
 
public void clear() {
this.keysAndValues.clear();
}
 
public int size() {
return this.keysAndValues.size() / 2;
}
 
public void dump(PrintStream out) {
for (int i = 0; i < size(); i++) {
out.print("(");
out.print(getKey(i));
out.print(")");
out.println(getValue(i));
}
out.flush();
}
 
public static GS1ApplicationIdentifier getApplicationIdentifier(String k) {
return GS1_128_AI.get(k);
}
 
public String formatHumanReadable() {
StringBuilder b = new StringBuilder();
int size = size();
for (int i = 0; i < size; i++) {
b.append('(');
b.append(this.getKey(i));
b.append(')');
b.append(this.getValue(i));
}
return b.toString();
}
}
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/gs1/GS1ApplicationIdentifier.java
New file
0,0 → 1,17
package org.openconcerto.modules.label.gs1;
 
public class GS1ApplicationIdentifier {
 
public final int minLength;
public final int length;
public final boolean variableLength;
public final boolean decimalPoint;
 
public GS1ApplicationIdentifier(int minLength, int length, boolean variableLength, boolean decimalPoint) {
this.minLength = minLength;
this.length = length;
this.variableLength = variableLength;
this.decimalPoint = decimalPoint;
}
}
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/gs1/GS1ParseException.java
New file
0,0 → 1,18
package org.openconcerto.modules.label.gs1;
 
public class GS1ParseException extends Exception {
final String ai;
final int errorCode;
final String errorMessage;
 
public GS1ParseException(final String ai, final int errorCode, final String errorMessage) {
this.ai = ai;
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
 
@Override
public String toString() {
return "AI: " + ai + ", errorCode: " + errorCode + ", errorMessage: " + errorMessage;
}
}
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/gs1/GS1Util.java
New file
0,0 → 1,243
package org.openconcerto.modules.label.gs1;
 
import org.openconcerto.modules.label.ISO646;
 
public class GS1Util {
 
// ISO/IEC 15424 symbology identifiers
// ]E0 : EAN-13, UPC-A, or UPC-E : 13 digits
// ]E1 : Two-digit add-on symbol : 2 digits
// ]E2 : Five-digit add-on symbol : 5 digits
// ]E3 : EAN-13, UPC-A, or UPC-E with add-on symbol : 15 or 18 digits
// ]E4 : EAN-8 : 8 digits
// ]I1 : ITF-14 : 14 digits
// ]C1 : GS1-128 : Standard AI element strings
private static final String GS1_128_SCANNER_PREFIX = "]C1";
// ]e0 : GS1 DataBar : Standard AI element strings
private static final String GS1_DATABAR_SCANNER_PREFIX = "]e0";
// ]e1 : GS1 Composite : Data packet containing the data + an encoded symbol separator
// character.
// ]e2 : GS1 Composite : Data packet containing the data following an escape mechanism
// character.
// ]d2 : GS1 DataMatrix : Standard AI element strings
private static final String GS1_DATAMATRIX_SCANNER_PREFIX = "]d2";
// ]Q3 : GS1 QR Code : Standard AI element strings
private static final String GS1_QRCODE_SCANNER_PREFIX = "]Q3";
// ]J1 : GS1 DotCode : Standard AI element strings
 
static final int ERROR_CODE_INVALID_GS1_SCAN = 0;
static final int ERROR_CODE_UNKNOWN_AI = 1;
static final int ERROR_CODE_INCOMPLETE_AI = 2;
static final int ERROR_CODE_NOT_FOUND_SEPARATOR = 3;
static final int ERROR_CODE_INSUFFICIENT_VALUE_LENGTH = 4;
static final int ERROR_CODE_EXCEEDED_VALUE_LENGTH = 5;
static final int ERROR_CODE_CONVERT_DECIMAL_POINT = 5;
static final int ERROR_CODE_WRONG_DECIMAL_POINT = 6;
static final int ERROR_CODE_CONVERT_DECIMAL_VALUE = 7;
 
public static final char GS_SEPARATOR = '\u001D';
// public static final char FNC1_SEPARATOR = 232;
 
static final int SPACE_SEPARATOR = ' ';
 
int separator;
 
public GS1Util() {
this(GS_SEPARATOR);
}
 
public GS1Util(int separator) {
this.separator = separator;
}
 
public GS1AIElements parseFromScanner(String scan) throws GS1ParseException {
if (scan.startsWith(GS1_DATAMATRIX_SCANNER_PREFIX) || scan.startsWith(GS1_128_SCANNER_PREFIX) || scan.startsWith(GS1_DATABAR_SCANNER_PREFIX) || scan.startsWith(GS1_QRCODE_SCANNER_PREFIX)) {
return parse(scan.substring(3));
}
return parse(scan);
}
 
public GS1AIElements parse(String barcode) throws GS1ParseException {
if (barcode.length() < 3) {
throw new GS1ParseException("", ERROR_CODE_INVALID_GS1_SCAN, "code too short");
}
 
System.err.println("GS1Util.parse()" + barcode);
GS1AIElements attr = new GS1AIElements();
StringBuilder ai = new StringBuilder();
 
int length = barcode.length();
for (int i = 0; i < length; ++i) {
int aiLength = ai.length();
if (aiLength > 1) {
GS1ApplicationIdentifier aii = GS1AIElements.getApplicationIdentifier(ai.toString());
if (aii == null) {
if (aiLength < 4)
ai.append(barcode.charAt(i));
else
throw new GS1ParseException(ai.toString(), ERROR_CODE_UNKNOWN_AI, "Unknown AI");
} else {
int decimalPoint = 0;
if (aii.decimalPoint) {
try {
decimalPoint = Integer.valueOf(String.valueOf(barcode.charAt(i)));
} catch (NumberFormatException e) {
throw new GS1ParseException(ai.toString(), ERROR_CODE_CONVERT_DECIMAL_POINT, "Errow convert to decimal point");
}
 
if (++i >= length)
throw new GS1ParseException(ai.toString(), ERROR_CODE_INSUFFICIENT_VALUE_LENGTH, "Insufficient value length");
}
 
String value;
 
if (aii.variableLength) {
int separatorIndex = barcode.indexOf(this.separator, i);
 
if (separatorIndex < 0) {
if (length - i > aii.length)
throw new GS1ParseException(ai.toString(), ERROR_CODE_NOT_FOUND_SEPARATOR, "Not found separator");
else if (length - i < aii.minLength)
throw new GS1ParseException(ai.toString(), ERROR_CODE_INSUFFICIENT_VALUE_LENGTH, "Insufficient value length");
else {
value = barcode.substring(i);
i = length;
}
} else if (separatorIndex - i > aii.length)
throw new GS1ParseException(ai.toString(), ERROR_CODE_EXCEEDED_VALUE_LENGTH, "Exceeded value length");
else if (separatorIndex - i < aii.minLength)
throw new GS1ParseException(ai.toString(), ERROR_CODE_INSUFFICIENT_VALUE_LENGTH, "Insufficient value length");
else {
value = barcode.substring(i, separatorIndex);
i = separatorIndex;
}
} else {
if (i + aii.length > length) {
throw new GS1ParseException(ai.toString(), ERROR_CODE_INSUFFICIENT_VALUE_LENGTH, "Insufficient value length");
}
value = barcode.substring(i, i + aii.length);
i += aii.length - 1;
}
 
if (aii.decimalPoint && decimalPoint > 0) {
if (decimalPoint >= value.length())
throw new GS1ParseException(ai.toString(), ERROR_CODE_WRONG_DECIMAL_POINT, "Decimal point more then value length");
 
try {
value = String.valueOf(Double.valueOf(value.substring(0, value.length() - decimalPoint) + "." + value.substring(value.length() - decimalPoint)));
} catch (NumberFormatException e) {
throw new GS1ParseException(ai.toString(), ERROR_CODE_CONVERT_DECIMAL_VALUE, "Error convert decimal point value");
}
}
 
attr.put(ai.toString(), value);
 
ai.setLength(0);
}
} else
ai.append(barcode.charAt(i));
}
 
if (ai.length() > 0)
throw new GS1ParseException(ai.toString(), ERROR_CODE_INCOMPLETE_AI, "Incomplete AI");
 
return attr;
}
 
public String format(GS1AIElements values) {
 
StringBuilder b = new StringBuilder();
int size = values.size();
for (int i = 0; i < size; i++) {
String k = values.getKey(i);
GS1ApplicationIdentifier ai = GS1AIElements.getApplicationIdentifier(k);
final String value = values.getValue(i);
b.append(k);
b.append(value);
if (ai.variableLength && i < size - 1) {
b.append((char) this.separator);
}
}
return b.toString();
}
 
public String formatZPL(GS1AIElements values) {
 
StringBuilder b = new StringBuilder();
int size = values.size();
b.append("@1");
for (int i = 0; i < size; i++) {
String k = values.getKey(i);
GS1ApplicationIdentifier ai = GS1AIElements.getApplicationIdentifier(k);
final String value = values.getValue(i);
b.append(k);
b.append(value);
if (ai.variableLength && i < size - 1) {
b.append("@d029");
}
}
return b.toString();
}
 
public String formatDataMatrix(GS1AIElements values) {
 
StringBuilder b = new StringBuilder();
int size = values.size();
// b.append(FNC1_SEPARATOR);
for (int i = 0; i < size; i++) {
String k = values.getKey(i);
GS1ApplicationIdentifier ai = GS1AIElements.getApplicationIdentifier(k);
final String value = values.getValue(i);
b.append('[');
b.append(k);
b.append(']');
b.append(value);
if (ai.variableLength && i < size - 1) {
// b.append(GS_SEPARATOR);
}
}
return b.toString();
}
 
public static void main(String[] args) throws GS1ParseException {
GS1Util p = new GS1Util('_');
System.out.println("GS1Util.main()" + (char) p.separator);
String barcode = "0104607018700852111806051718062910180605_211";
// barcode = "01088888931021461712031510W1040190";
GS1AIElements values = p.parse(barcode);
values.dump(System.out);
 
values.put("391", "kookkk");
System.out.println(p.format(values));
System.out.println(values.formatHumanReadable());
 
GS1AIElements valuesMax = new GS1AIElements();
valuesMax.put("02", "01234567891234");
valuesMax.put("15", "201202");
valuesMax.put("37", "12345678");
valuesMax.put("10", "12345678901234567890");
GS1Util pStd = new GS1Util();
System.out.println(p.format(valuesMax));
System.out.println(p.format(valuesMax).length());
System.out.println(pStd.format(valuesMax));
System.out.println(pStd.format(valuesMax).length());
System.err.println("GS1Util.main() GS128 from barcode reader");
String gs1128 = "]C10207612345678900152012153745646578";
GS1Util p2 = new GS1Util();
values = p2.parseFromScanner(gs1128);
values.dump(System.out);
}
 
public static String showAllChars(String s) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (ISO646.isValid(s.charAt(i))) {
b.append(s.charAt(i));
} else {
b.append("[" + (int) s.charAt(i) + "]");
}
}
return b.toString();
}
 
}
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/graphicspl/GPLRenderer.java
New file
0,0 → 1,166
package org.openconcerto.modules.label.graphicspl;
 
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
 
import javax.imageio.ImageIO;
 
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
 
public abstract class GPLRenderer {
public static final int ALIGN_LEFT = 0;
public static final int ALIGN_RIGHT = 1;
public static final int ALIGN_CENTER = 2;
 
public static final int BARCODE_EAN8 = 0;
public static final int BARCODE_EAN13 = 1;
public static final int BARCODE_CODE128 = 2;
public static final int BARCODE_CODE128_GS1 = 3;
public static final int BARCODE_DATAMATRIX = 4;
public static final int BARCODE_QRCODE = 5;
private final float ratio;
 
public GPLRenderer(float ratio) {
this.ratio = ratio;
}
 
public GPLRenderer() {
this.ratio = 1.0f;
}
 
public float getRatio() {
return ratio;
}
 
public void render(GraphicsPL graphicsPL) throws IOException {
 
Document doc = graphicsPL.getDocument();
final int width = Integer.parseInt(doc.getDocumentElement().getAttribute("width"));
NodeList nodeList = doc.getFirstChild().getChildNodes();
int size = nodeList.getLength();
for (int i = 0; i < size; i++) {
 
if (nodeList.item(i).getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) nodeList.item(i);
String name = element.getNodeName();
if (name.equals("text")) {
int x = Math.round(ratio * Integer.parseInt(element.getAttribute("x")));
int y = Math.round(ratio * Integer.parseInt(element.getAttribute("y")));
String txt = element.getTextContent();
Color color = Color.BLACK;
if (element.hasAttribute("color")) {
color = Color.decode(element.getAttribute("color"));
}
int fontSize = Math.round(ratio * Integer.parseInt(element.getAttribute("fontsize")));
String fontName = element.getAttribute("font");
int maxWidth = width - x;
boolean wrap = false;
int align = ALIGN_LEFT;
if (element.hasAttribute("align")) {
if (element.getAttribute("align").equals("right")) {
align = ALIGN_RIGHT;
} else if (element.getAttribute("align").equals("center")) {
align = ALIGN_CENTER;
}
}
if (!element.hasAttribute("visible") || element.getAttribute("visible").equals("true")) {
drawText(x, y, txt, align, fontName, fontSize, color, maxWidth, wrap);
}
 
} else if (name.equals("rectangle")) {
int x = Math.round(ratio * Integer.parseInt(element.getAttribute("x")));
int y = Math.round(ratio * Integer.parseInt(element.getAttribute("y")));
int w = Math.round(ratio * Integer.parseInt(element.getAttribute("width")));
int h = Math.round(ratio * Integer.parseInt(element.getAttribute("height")));
Color color = Color.BLACK;
if (element.hasAttribute("color")) {
color = Color.decode(element.getAttribute("color"));
}
 
if (element.hasAttribute("fill") && element.getAttribute("fill").equals("true")) {
fillRectangle(x, y, w, h, color);
} else {
int lineWidth = Math.round(ratio);
if (element.hasAttribute("linewidth")) {
lineWidth = Math.round(ratio * Integer.parseInt(element.getAttribute("linewidth")));
}
drawRectangle(x, y, w, h, color, lineWidth);
}
 
} else if (name.equals("image")) {
String fileName = element.getAttribute("file");
int x = Math.round(ratio * Integer.parseInt(element.getAttribute("x")));
int y = Math.round(ratio * Integer.parseInt(element.getAttribute("y")));
BufferedImage img = ImageIO.read(new File(graphicsPL.getImageDir(), fileName));
int w = Math.round(ratio * img.getWidth());
int h = Math.round(ratio * img.getHeight());
if (element.hasAttribute("width")) {
w = Math.round(ratio * Integer.parseInt(element.getAttribute("width")));
}
if (element.hasAttribute("height")) {
h = Math.round(ratio * Integer.parseInt(element.getAttribute("height")));
}
drawImage(x, y, w, h, img);
 
} else if (name.equals("barcode")) {
int x = Math.round(ratio * Integer.parseInt(element.getAttribute("x")));
int y = Math.round(ratio * Integer.parseInt(element.getAttribute("y")));
int h = 0;
 
if (element.hasAttribute("height")) {
h = Math.round(ratio * Integer.parseInt(element.getAttribute("height")));
}
String type = element.getAttribute("type");
String code = element.getTextContent();
int t;
if (type.equals("ean8")) {
t = BARCODE_EAN8;
} else if (type.equals("ean13")) {
t = BARCODE_EAN13;
} else if (type.equals("ean128")) {
t = BARCODE_CODE128;
} else if (type.equals("gs1")) {
t = BARCODE_CODE128_GS1;
} else if (type.equals("datamatrix")) {
t = BARCODE_DATAMATRIX;
if (h != 0) {
System.err.println("ignoring datamatrix height attribute");
}
} else if (type.equals("qrcode")) {
t = BARCODE_QRCODE;
} else {
throw new IllegalArgumentException("unsupported barcode type : " + type);
}
 
int fontSize = Math.round(ratio * 8);
if (element.hasAttribute("fontsize")) {
fontSize = Math.round(ratio * Integer.parseInt(element.getAttribute("fontsize")));
}
int moduleWidth = Math.round(ratio);
if (element.hasAttribute("modulewidth")) {
moduleWidth = Math.round(ratio * Integer.parseInt(element.getAttribute("modulewidth")));
}
drawBarcode(x, y, h, t, code, moduleWidth, fontSize);
} else {
throw new IllegalStateException("unsupported primitive : " + name);
}
}
}
}
 
public abstract void drawText(int x, int y, String text, int align, String fontName, int fontSize, Color color, int maxWidth, boolean wrap);
 
public abstract void drawImage(int x, int y, int w, int h, BufferedImage img);
 
public abstract void fillRectangle(int x, int y, int w, int h, Color color);
 
public abstract void drawRectangle(int x, int y, int w, int h, Color color, int lineWidth);
 
public abstract void drawBarcode(int x, int y, int h, int type, String code, int moduleWidth, int fontSize);
 
}
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/graphicspl/GraphicsPL.java
New file
0,0 → 1,128
package org.openconcerto.modules.label.graphicspl;
 
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
 
import javax.imageio.ImageIO;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
 
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
 
public class GraphicsPL {
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><graphicspl height=\"400\" width=\"600\"/>";
Document doc;
private File imgDir;
 
public static void main(String[] args) throws Exception {
GraphicsPL g = new GraphicsPL();
g.load(new File("Template/Labels/test.graphicspl"));
BufferedImage img = g.createImage(10);
ImageIO.write(img, "png", new File("gpl.png"));
String zpl = g.getZPL();
System.out.println(zpl);
Printable p = g.createPrintable();
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(p);
boolean ok = job.printDialog();
if (ok) {
job.print();
}
 
}
 
public Printable createPrintable() {
final Element root = this.doc.getDocumentElement();
int dpi = 300;
if (root.hasAttribute("dpi")) {
dpi = Integer.parseInt(root.getAttribute("dpi"));
}
float printRatio = 1f;
if (root.hasAttribute("printratio")) {
printRatio = Float.parseFloat(root.getAttribute("printratio"));
}
return createPrintable(dpi, printRatio);
}
 
public Printable createPrintable(int dpi, float printRatio) {
return new Printable() {
 
@Override
public int print(Graphics graphics, PageFormat pf, int pageIndex) throws PrinterException {
if (pageIndex > 0) {
return NO_SUCH_PAGE;
}
final Element root = GraphicsPL.this.doc.getDocumentElement();
final int width = Math.round(printRatio * Integer.parseInt(root.getAttribute("width")));
final int height = Math.round(printRatio * Integer.parseInt(root.getAttribute("height")));
final Graphics2D g2d = (Graphics2D) graphics;
float ratio = (printRatio * dpi) / 72f;
try {
final BufferedImage img = createImage(ratio);
g2d.drawImage(img, (int) Math.round(pf.getImageableX()), (int) Math.round(pf.getImageableY()), width, height, null);
} catch (ParserConfigurationException | SAXException | IOException e) {
throw new PrinterException(e.getMessage());
}
return PAGE_EXISTS;
}
};
}
 
private String getZPL() throws IOException {
final ZPLRenderer renderer = new ZPLRenderer();
renderer.render(this);
return renderer.getZPL();
}
 
private BufferedImage createImage(float ratio) throws ParserConfigurationException, SAXException, IOException {
final Element root = this.doc.getDocumentElement();
final int width = Math.round(ratio * Integer.parseInt(root.getAttribute("width")));
final int height = Math.round(ratio * Integer.parseInt(root.getAttribute("height")));
final BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
final Graphics2D graphics = (Graphics2D) img.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, width, height);
final Graphics2DRenderer renderer = new Graphics2DRenderer(graphics, ratio);
renderer.render(this);
graphics.dispose();
return img;
}
 
public Document getDocument() {
return this.doc;
}
 
private void load(File file) throws ParserConfigurationException, SAXException, IOException {
this.xml = new String(Files.readAllBytes(file.toPath()));
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
final DocumentBuilder builder = factory.newDocumentBuilder();
final ByteArrayInputStream input = new ByteArrayInputStream(this.xml.getBytes(StandardCharsets.UTF_8));
this.doc = builder.parse(input);
this.doc.getDocumentElement().normalize();
this.imgDir = file.getParentFile();
}
 
public File getImageDir() {
return this.imgDir;
}
 
public void setImageDir(File dir) {
this.imgDir = dir;
}
 
}
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/graphicspl/ZPLRenderer.java
New file
0,0 → 1,234
package org.openconcerto.modules.label.graphicspl;
 
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
 
import org.openconcerto.utils.ImageUtils;
import org.openconcerto.utils.StringUtils;
 
public class ZPLRenderer extends GPLRenderer {
 
private StringBuilder sb = new StringBuilder();
 
public ZPLRenderer() {
sb.append("^XA\n^CI28\n");
}
 
@Override
public void drawText(int x, int y, String text, int align, String fontName, int fontSize, Color color, int maxWidth, boolean wrap) {
sb.append("^CF0,");
sb.append(fontSize);
//
 
if (align == ALIGN_RIGHT) {
sb.append("^FO");
sb.append('0');
sb.append(',');
sb.append(y);
sb.append("^FB");
sb.append(x);
sb.append(",9999,0");
 
sb.append(",R,0");
} else if (align == ALIGN_CENTER) {
sb.append("^FO");
sb.append('0');
sb.append(',');
sb.append(y);
sb.append("^FB");
sb.append(x * 2);
sb.append(",9999,0");
 
sb.append(",C,0");
} else {
sb.append("^FO");
sb.append(x);
sb.append(',');
sb.append(y);
 
//
sb.append("^FB");
sb.append(maxWidth);
sb.append(",9999,0");
 
sb.append(",L,0");
}
//
 
sb.append("^FD");
sb.append(text);
if (align == ALIGN_CENTER) {
sb.append("\\&");
}
 
sb.append("^FS\n");
}
 
@Override
public void drawImage(int x, int y, int w, int h, BufferedImage img) {
try {
if (w != img.getWidth() || h != img.getHeight()) {
img = ImageUtils.createQualityResizedImage(img, w, h);
}
 
final int bytesPerRow = (img.getWidth() + 7) / 8;
int size = bytesPerRow * img.getHeight();
byte[] data = getData(img);
sb.append("^FO");
sb.append(x);
sb.append(",");
sb.append(y);
sb.append("^GFA");
sb.append(",");
sb.append(size);
sb.append(",");
sb.append(size);
sb.append(",");
sb.append(bytesPerRow);
sb.append(",");
sb.append(StringUtils.bytesToHexString(data));
sb.append("^FS\n");
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
 
byte[] getData(BufferedImage img) throws IOException {
 
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
int width = img.getWidth();
 
int height = img.getHeight();
// Lines
for (int i = 0; i < height; i++) {
int[] pixels = new int[width];
img.getRGB(0, i, width, 1, pixels, 0, 4);
final byte[] encodedLine = encodeLine(pixels);
out.write(encodedLine);
}
return out.toByteArray();
}
 
private byte[] encodeLine(int[] pixels) throws IOException {
final int bytesPerRow = (pixels.length + 7) / 8;
byte[] bytesToEncode = new byte[bytesPerRow];
int index = 0;
for (int i = 0; i < bytesToEncode.length; i++) {
int points = 0;
for (int j = 0; j < 8; j++) {
 
int c = 0;
if (index < pixels.length) {
c = pixels[index];
int a = (c & 0xff000000) >> 24;
int r = (c & 0x00ff0000) >> 16;
int g = (c & 0x0000ff00) >> 8;
int b = c & 0x000000ff;
int grayScale = (int) (21.2671 * r + 71.5160 * g + 7.2169 * b);
boolean isBlack = grayScale < 12000;
points = points * 2;
if (isBlack && a < 0) {
points++;
}
 
} else {
points = points * 2;
}
 
index++;
}
bytesToEncode[i] = (byte) points;
 
}
return bytesToEncode;
}
 
@Override
public void fillRectangle(int x, int y, int w, int h, Color color) {
sb.append("^FO");
sb.append(x);
sb.append(',');
sb.append(y);
 
sb.append("^GB");
sb.append(w);
sb.append(',');
sb.append(h);
sb.append(',');
sb.append(Math.min(w, h));
sb.append("^FS\n");
 
}
 
@Override
public void drawRectangle(int x, int y, int w, int h, Color color, int lineWidth) {
sb.append("^FO");
sb.append(x);
sb.append(',');
sb.append(y);
 
sb.append("^GB");
sb.append(w);
sb.append(',');
sb.append(h);
sb.append(',');
sb.append(lineWidth);
sb.append("^FS\n");
}
 
@Override
public void drawBarcode(int x, int y, int h, int type, String code, int moduleWidth, int fontSize) {
code = code.trim();
sb.append("^FO");
sb.append(x);
sb.append(',');
sb.append(y);
sb.append("^CF0,");
sb.append(fontSize);
if (type == BARCODE_EAN13) {
sb.append("^BY");
sb.append(moduleWidth);
 
sb.append("^BEN,");
sb.append(h);
sb.append(",Y,N");
 
} else if (type == BARCODE_EAN8) {
sb.append("^BY");
sb.append(moduleWidth);
 
sb.append("^B8N,");
sb.append(h);
sb.append(",Y,N");
 
} else if (type == BARCODE_DATAMATRIX) {
sb.append("^BXN,");
sb.append(moduleWidth);
sb.append(",200");
} else if (type == BARCODE_CODE128) {
sb.append("^BY");
sb.append(moduleWidth - 1);
sb.append("^BCN,");
sb.append(h);
sb.append(",Y,N,Y,D");
 
} else if (type == BARCODE_CODE128_GS1) {
sb.append("^BY");
sb.append(moduleWidth - 1);
sb.append("^BCN,");
sb.append(h);
sb.append(",Y,N,Y,N");
 
}
sb.append("^FD");
sb.append(code);
sb.append("^FS\n");
}
 
public String getZPL() {
return sb.toString() + "\n^XZ";
}
 
}
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/graphicspl/Graphics2DRenderer.java
New file
0,0 → 1,116
package org.openconcerto.modules.label.graphicspl;
 
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
 
import uk.org.okapibarcode.backend.Code128;
import uk.org.okapibarcode.backend.DataMatrix;
import uk.org.okapibarcode.backend.Ean;
import uk.org.okapibarcode.backend.QrCode;
import uk.org.okapibarcode.backend.Symbol;
import uk.org.okapibarcode.output.Java2DRenderer;
 
public class Graphics2DRenderer extends GPLRenderer {
 
private final Graphics2D g;
 
public Graphics2DRenderer(Graphics2D g, float ratio) {
super(ratio);
this.g = g;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
}
 
@Override
public void drawText(int x, int y, String text, int align, String fontName, int fontSize, Color color, int maxWidth, boolean wrap) {
final Font font = new Font(fontName, Font.PLAIN, fontSize);
g.setFont(font.deriveFont(fontSize));
g.setColor(color);
y += g.getFontMetrics().getAscent() - g.getFontMetrics().getDescent();
if (align == ALIGN_RIGHT) {
int w = (int) g.getFontMetrics().getStringBounds(text, g).getWidth();
g.drawString(text, x - w, y);
} else if (align == ALIGN_CENTER) {
int w = (int) (g.getFontMetrics().getStringBounds(text, g).getWidth() / 2D);
g.drawString(text, x - w, y);
} else {
g.drawString(text, x, y);
}
}
 
@Override
public void drawImage(int x, int y, int w, int h, BufferedImage img) {
g.drawImage(img, x, y, x + w, y + h, 0, 0, img.getWidth(), img.getHeight(), null);
}
 
@Override
public void fillRectangle(int x, int y, int w, int h, Color color) {
g.setColor(color);
g.fillRect(x, y, w, h);
}
 
@Override
public void drawRectangle(int x, int y, int w, int h, Color color, int lineWidth) {
Stroke s = g.getStroke();
g.setColor(color);
if (lineWidth != 1) {
g.setStroke(new BasicStroke(lineWidth));
}
g.drawRect(x, y, w, h);
g.setStroke(s);
}
 
@Override
public void drawBarcode(int x, int y, int h, int type, String code, int moduleWidth, int fontSize) {
 
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
 
Symbol symbol = null;
if (type == BARCODE_EAN8) {
symbol = new Ean();
((Ean) symbol).setMode(Ean.Mode.EAN8);
symbol.setBarHeight(h);
} else if (type == BARCODE_EAN13) {
symbol = new Ean();
((Ean) symbol).setMode(Ean.Mode.EAN13);
symbol.setBarHeight(h);
} else if (type == BARCODE_CODE128) {
symbol = new Code128();
symbol.setDataType(Symbol.DataType.GS1);
symbol.setBarHeight(h);
} else if (type == BARCODE_CODE128_GS1) {
symbol = new Code128();
symbol.setBarHeight(h);
} else if (type == BARCODE_DATAMATRIX) {
symbol = new DataMatrix();
} else if (type == BARCODE_QRCODE) {
symbol = new QrCode();
}
 
if (symbol == null) {
return;
}
symbol.setModuleWidth(moduleWidth);
symbol.setFontSize(fontSize);
symbol.setContent(code.trim());
 
AffineTransform aT = g.getTransform();
 
g.setTransform(AffineTransform.getTranslateInstance(x, y));
 
Java2DRenderer renderer = new Java2DRenderer(g, 1, Color.WHITE, Color.BLACK);
renderer.render(symbol);
 
g.setTransform(aT);
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
 
}
 
}
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/oc-qrcode.png
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/oc-qrcode.png
New file
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/Label.java
New file
0,0 → 1,5
package org.openconcerto.modules.label;
 
public class Label {
 
}
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/default-zpl.txt
New file
0,0 → 1,20
^XA
 
^FX Titre
^CF0,42^FO150,43^FB750,1,0,L^FDXXXXXXXXXX^FS
^FX DataMatrix
^FO1010,20^BXN,7,200,,,,@^FDOPENCONCERTO^FS
 
^FX Nom du produit
^CF0,40
^FO150,140^FB700,1,0,L^FDYYYYYYYYYY^FS
 
^FX Code barre
^FO150,220
^BY3,2,300
^BCN,300,Y,N,Y,D
^FD(02)7612345678900(15)201218(37)9999^FS
 
^FO150,620^BY3,2,300^BCN,300,Y,N,Y,D^FD(10)LLLLLLLLL^FS
 
^XZ
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/ModuleLabel.java
4,10 → 4,17
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.TreeMap;
 
import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.SwingWorker;
 
import org.openconcerto.erp.generationDoc.provider.AdresseFullClientValueProvider;
14,6 → 21,7
import org.openconcerto.erp.modules.AbstractModule;
import org.openconcerto.erp.modules.ComponentsContext;
import org.openconcerto.erp.modules.ModuleFactory;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
23,10 → 31,12
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.FileUtils;
import org.openconcerto.utils.GestionDevise;
import org.openconcerto.utils.StringUtils;
 
public final class ModuleLabel extends AbstractModule {
final LinkedHashMap<String, String> zplTemplates = new LinkedHashMap<String, String>();
 
public ModuleLabel(ModuleFactory f) throws IOException {
super(f);
34,6 → 44,9
 
@Override
protected void setupComponents(ComponentsContext ctxt) {
readTemplates(new File("Template/Labels"));
readTemplates(new File("Configuration/Template/Labels"));
 
final String actionName = "Imprimer les étiquettes";
final PredicateRowAction aArticle = new PredicateRowAction(new AbstractAction(actionName) {
 
41,26 → 54,31
public void actionPerformed(ActionEvent arg0) {
final IListe list = IListe.get(arg0);
final List<Integer> selectedIDs = list.getSelection().getSelectedIDs();
final SwingWorker<List<SQLRowValues>, String> wworker = new SwingWorker<List<SQLRowValues>, String>() {
final SQLTable tArticle = list.getSelectedRows().get(0).getTable();
final SwingWorker<List<RowValuesLabel>, String> wworker = new SwingWorker<List<RowValuesLabel>, String>() {
 
@Override
protected List<SQLRowValues> doInBackground() throws Exception {
final SQLTable tArticle = list.getSelectedRows().get(0).getTable();
protected List<RowValuesLabel> doInBackground() throws Exception {
final SQLRowValues graph = new SQLRowValues(tArticle);
graph.putNulls("NOM", "PV_TTC");
final SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(graph);
final List<SQLRowValues> values = fetcher.fetch(new Where(tArticle.getKey(), selectedIDs));
return values;
final List<SQLRowValues> rows = fetcher.fetch(new Where(tArticle.getKey(), selectedIDs));
final List<RowValuesLabel> list = new ArrayList<>(rows.size());
for (SQLRowValues row : rows) {
list.add(new RowValuesLabel(row));
}
return list;
}
 
@Override
protected void done() {
try {
final List<SQLRowValues> values = get();
final List<RowValuesLabel> values = get();
 
final LabelFrame f = new LabelFrame(values, new LabelRenderer() {
 
@Override
public void paintLabel(Graphics g, SQLRowAccessor row, int x, int y, int gridWith, int gridHeight, float fontSize) {
public void paintLabel(Graphics g, Label label, int x, int y, int gridWith, int gridHeight, float fontSize) {
g.setColor(Color.BLACK);
g.setFont(g.getFont().deriveFont(fontSize));
// Labels borders
67,6 → 85,7
final int hBorder = 12;
final int vBorder = 8;
// Product name
SQLRowValues row = ((RowValuesLabel) label).getSQLRowValues();
final String text = row.getString("NOM");
final List<String> l = StringUtils.wrap(text, g.getFontMetrics(), gridWith - 2 * hBorder);
final int lineHeight = g.getFontMetrics().getHeight();
73,7 → 92,7
int lineY = y;
final int margin = gridHeight - l.size() * lineHeight;
if (margin > 0) {
lineY += (int) (margin / 2);
lineY += margin / 2;
}
for (String line : l) {
g.drawString(line, x + hBorder, lineY);
95,7 → 114,7
} catch (Exception e) {
ExceptionHandler.handle("Erreur d'impression", e);
}
};
}
};
wworker.execute();
 
107,11 → 126,11
public void actionPerformed(ActionEvent arg0) {
final IListe list = IListe.get(arg0);
final List<Integer> selectedIDs = list.getSelection().getSelectedIDs();
final SwingWorker<List<SQLRowValues>, String> wworker = new SwingWorker<List<SQLRowValues>, String>() {
final SQLTable tClient = list.getSelectedRows().get(0).getTable();
final SwingWorker<List<RowValuesLabel>, String> wworker = new SwingWorker<List<RowValuesLabel>, String>() {
 
@Override
protected List<SQLRowValues> doInBackground() throws Exception {
final SQLTable tClient = list.getSelectedRows().get(0).getTable();
protected List<RowValuesLabel> doInBackground() throws Exception {
final SQLRowValues graph = new SQLRowValues(tClient);
graph.putNulls("NOM");
final SQLRowValues a1 = graph.putRowValues("ID_ADRESSE");
119,17 → 138,24
final SQLRowValues a2 = graph.putRowValues("ID_ADRESSE_L");
a2.putNulls(a2.getTable().getFieldsName());
final SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(graph);
final List<SQLRowValues> values = fetcher.fetch(new Where(tClient.getKey(), selectedIDs));
return values;
final List<SQLRowValues> rows = fetcher.fetch(new Where(tClient.getKey(), selectedIDs));
 
final List<RowValuesLabel> list = new ArrayList<>(rows.size());
for (SQLRowValues row : rows) {
list.add(new RowValuesLabel(row));
}
return list;
}
 
@Override
protected void done() {
try {
final List<SQLRowValues> values = get();
final List<RowValuesLabel> values = get();
final LabelFrame f = new LabelFrame(values, new LabelRenderer() {
 
@Override
public void paintLabel(Graphics g, SQLRowAccessor row, int x, int y, int gridWith, int gridHeight, float fontSize) {
public void paintLabel(Graphics g, Label label, int x, int y, int gridWith, int gridHeight, float fontSize) {
SQLRowValues row = ((RowValuesLabel) label).getSQLRowValues();
SQLRowAccessor rAddr = row.getForeign("ID_ADRESSE_L");
if (rAddr == null || rAddr.isUndefined()) {
rAddr = row.getForeign("ID_ADRESSE");
165,7 → 191,7
} catch (Exception e) {
ExceptionHandler.handle("Erreur d'impression", e);
}
};
}
};
wworker.execute();
 
176,13 → 202,94
aClient.setPredicate(IListeEvent.createSelectionCountPredicate(1, Integer.MAX_VALUE));
ctxt.getElement("ARTICLE").getRowActions().add(aArticle);
ctxt.getElement("CLIENT").getRowActions().add(aClient);
 
if (!this.zplTemplates.isEmpty()) {
for (final Entry<String, String> entry : this.zplTemplates.entrySet()) {
final String zpl = entry.getValue();
final PredicateRowAction action = new PredicateRowAction(new AbstractAction("Imprimer l'étiquette " + entry.getKey()) {
 
@Override
public void actionPerformed(ActionEvent arg0) {
final ZPLPrinterPanel p = new ZPLPrinterPanel(zpl);
final JFrame f = new JFrame();
final IListe list = IListe.get(arg0);
final int idProduct = list.getSelection().getSelectedID();
final SQLTable tArticle = list.getSelectedRows().get(0).getTable();
 
final SwingWorker<SQLRowValues, String> wworker = new SwingWorker<SQLRowValues, String>() {
 
@Override
protected SQLRowValues doInBackground() throws Exception {
final SQLRow row = tArticle.getRow(idProduct);
row.fetchValues();
return row.asRowValues();
}
 
@Override
protected void done() {
try {
final SQLRowValues values = get();
p.initUI(values);
f.setTitle(entry.getKey());
f.setContentPane(p);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
 
} catch (Exception e) {
ExceptionHandler.handle("Erreur d'impression", e);
}
}
};
wworker.execute();
 
}
}, true, false);
 
action.setPredicate(IListeEvent.createSelectionCountPredicate(1, 1));
ctxt.getElement("ARTICLE").getRowActions().add(action);
}
}
 
}
 
@Override
protected void start() {
 
}
 
private void readTemplates(File templatesDir) {
System.out.println("ModuleLabel.readTemplates() " + templatesDir.getAbsolutePath());
if (templatesDir.exists() && templatesDir.isDirectory()) {
System.err.println("ModuleLabel.readTemplates() " + templatesDir.getAbsolutePath());
File[] files = templatesDir.listFiles();
if (files != null) {
LinkedHashMap<String, String> map = new LinkedHashMap<>();
for (File f : files) {
if (f.getName().endsWith(".zpl")) {
try {
String zpl = FileUtils.read(f, StandardCharsets.UTF_8);
String name = f.getName().substring(0, f.getName().length() - 4).trim();
map.put(name, zpl);
System.err.println("ModuleLabel.readTemplates() add " + name);
} catch (Exception e) {
System.err.println(this.getClass().getCanonicalName() + "start() cannot read zpl template : " + f.getAbsolutePath() + " : " + e.getMessage());
}
}
}
// Tri de la map par clef
final TreeMap<String, String> copy = new TreeMap<>(map);
this.zplTemplates.clear();
this.zplTemplates.putAll(copy);
}
 
} else {
System.err.println("ModuleLabel.readTemplates() " + templatesDir.getAbsolutePath() + " missing");
}
}
 
@Override
protected void stop() {
// nothing
}
}
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/32.png
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/32.png
New file
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/RowValuesLabel.java
New file
0,0 → 1,16
package org.openconcerto.modules.label;
 
import org.openconcerto.sql.model.SQLRowValues;
 
public class RowValuesLabel extends Label {
private SQLRowValues row;
 
public RowValuesLabel(SQLRowValues row) {
this.row = row;
}
 
public SQLRowValues getSQLRowValues() {
return row;
}
 
}
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/16.png
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/16.png
New file
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/ZPLPrinterPanel.java
New file
0,0 → 1,409
package org.openconcerto.modules.label;
 
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.print.PrinterJob;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
 
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.SimpleDoc;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
 
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.JLabelBold;
import org.openconcerto.utils.BaseDirs;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.FileUtils;
import org.openconcerto.utils.ProductInfo;
 
public class ZPLPrinterPanel extends JPanel {
private final HashMap<String, String> mapName = new HashMap<>();
private final List<String> variables;
private final List<String> knownVariables = new ArrayList<>();
private Map<String, JTextField> editorMap = new HashMap<>();
private String zpl;
private final Properties properties = new Properties();
 
public static void main(String[] args) throws IOException {
// final File f = new File("Templates/Labels", "50x50.zpl");
final File file = new File("Template/Labels", "57x32.zpl");
String zpl = FileUtils.read(file);
SwingUtilities.invokeLater(new Runnable() {
 
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
ZPLPrinterPanel p = new ZPLPrinterPanel(zpl);
p.initUI(null);
JFrame f = new JFrame();
f.setTitle(file.getName());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(p);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
 
}
 
public ZPLPrinterPanel(String zpl) {
this.zpl = zpl;
this.variables = getVariables(zpl);
knownVariables.add("product.code");
knownVariables.add("product.name");
knownVariables.add("product.material");
 
knownVariables.add("product.ean13");
knownVariables.add("product.price");
knownVariables.add("product.pricewithtax");
//
mapName.put("product.name", "Nom");
mapName.put("product.code", "Code");
mapName.put("product.ean13", "Code à barres");
mapName.put("product.price", "Prix HT");
mapName.put("product.pricewithtax", "Prix TTC");
mapName.put("product.treatment", "Traitement");
mapName.put("product.origin", "Origine");
mapName.put("product.batch", "Lot");
mapName.put("product.size", "Taille");
mapName.put("product.color", "Couleur");
mapName.put("product.material", "Matière");
}
 
private final File getPrefFile() {
final File prefsFolder = BaseDirs.create(ProductInfo.getInstance()).getPreferencesFolder();
if (!prefsFolder.exists()) {
prefsFolder.mkdirs();
}
return new File(prefsFolder, "labels.properties");
}
 
protected void initUI(SQLRowAccessor row) {
final File prefsFolder = BaseDirs.create(ProductInfo.getInstance()).getPreferencesFolder();
if (!prefsFolder.exists()) {
prefsFolder.mkdirs();
}
 
final File file = getPrefFile();
System.out.println(file.getAbsolutePath());
if (file.exists()) {
try {
properties.load(new FileInputStream(file));
} catch (IOException e) {
e.printStackTrace();
}
}
 
this.setLayout(new GridBagLayout());
GridBagConstraints c = new DefaultGridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
this.removeAll();
 
// Fields
 
Set<String> added = new HashSet<>();
for (String v : this.knownVariables) {
if (variables.contains(v)) {
// Non editable
String label = getName(v);
c.gridx = 0;
c.weightx = 0;
this.add(new JLabel(label, SwingConstants.RIGHT), c);
c.gridx++;
c.weightx = 1;
 
String value = getValueAsString(row, v);
JTextField txt = new JTextField(20);
if (value != null) {
txt.setText(value);
txt.setEditable(false);
}
editorMap.put(v, txt);
this.add(txt, c);
added.add(v);
c.gridy++;
}
}
for (String v : this.variables) {
if (!added.contains(v)) {
// Editable
String label = getName(v);
c.gridx = 0;
c.weightx = 0;
this.add(new JLabel(label, SwingConstants.RIGHT), c);
c.gridx++;
c.weightx = 1;
JTextField txt = new JTextField(20);
editorMap.put(v, txt);
this.add(txt, c);
added.add(v);
c.gridy++;
}
 
}
 
c.gridwidth = 2;
c.gridx = 0;
this.add(new JLabelBold("Paramètres d'impression"), c);
// Printer selector
c.gridx = 0;
c.gridy++;
final JPanel l1 = new JPanel();
l1.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 0));
 
l1.add(new JLabel("Nombre d'étiquettes"));
final JSpinner nbLabels = new JSpinner(new SpinnerNumberModel(1, 1, 1000, 10));
l1.add(nbLabels);
this.add(l1, c);
// Delay
l1.add(new JLabel(" Pause entre chaque impression"));
final JSpinner delayLabels = new JSpinner(new SpinnerNumberModel(800, 100, 10000, 100));
l1.add(delayLabels);
this.add(l1, c);
l1.add(new JLabel("ms"));
 
c.gridy++;
 
final JPanel lPrintNetwork = new JPanel();
lPrintNetwork.setLayout(new FlowLayout(FlowLayout.LEFT, 2, 0));
JRadioButton radioNetworkPrinter = new JRadioButton("imprimante réseau IP :");
lPrintNetwork.add(radioNetworkPrinter);
JTextField textPrinterIP = new JTextField(16);
lPrintNetwork.add(textPrinterIP);
lPrintNetwork.add(new JLabel(" Port :"));
JSpinner portZPL = new JSpinner(new SpinnerNumberModel(9100, 24, 10000, 1));
lPrintNetwork.add(portZPL);
this.add(lPrintNetwork, c);
 
c.gridy++;
final JPanel lPrintLocal = new JPanel();
lPrintLocal.setLayout(new FlowLayout(FlowLayout.LEFT, 2, 0));
JRadioButton radioLocalPrinter = new JRadioButton("imprimante locale");
lPrintLocal.add(radioLocalPrinter);
radioLocalPrinter.setSelected(true);
this.add(lPrintLocal, c);
 
final ButtonGroup gr = new ButtonGroup();
gr.add(radioLocalPrinter);
gr.add(radioNetworkPrinter);
c.gridy++;
c.weighty = 1;
c.gridx = 1;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.SOUTHEAST;
 
// Restore state from properties
if (properties.getOrDefault("printerType", "local").equals("local")) {
radioLocalPrinter.setSelected(true);
} else {
radioNetworkPrinter.setSelected(true);
}
textPrinterIP.setText(properties.getOrDefault("printerIp", "").toString());
portZPL.setValue(Long.parseLong(properties.getOrDefault("printerPort", "9100").toString()));
nbLabels.setValue(Long.parseLong(properties.getOrDefault("nbLabels", "1").toString()));
delayLabels.setValue(Long.parseLong(properties.getOrDefault("delay", "800").toString()));
// Print
 
JButton printButton = new JButton("Imprimer");
this.add(printButton, c);
printButton.addActionListener(new ActionListener() {
 
@Override
public void actionPerformed(ActionEvent e) {
try {
if (radioLocalPrinter.isSelected()) {
properties.put("printerType", "local");
} else {
properties.put("printerType", "network");
properties.put("printerIp", textPrinterIP.getText());
properties.put("printerPort", portZPL.getValue().toString());
}
properties.put("nbLabels", nbLabels.getValue().toString());
properties.put("delay", delayLabels.getValue().toString());
// Save Prefs
properties.store(new FileOutputStream(getPrefFile()), "");
} catch (Exception e1) {
ExceptionHandler.handle("Erreur de sauvegarde de " + getPrefFile().getAbsolutePath(), e1);
}
final String code = createZPLCode();
System.out.println("ZPL:");
System.out.println(code);
byte[] data = code.getBytes(StandardCharsets.UTF_8);
if (radioNetworkPrinter.isSelected()) {
Socket socket = null;
try {
socket = new Socket(textPrinterIP.getText(), ((Number) portZPL.getValue()).intValue());
final DataOutputStream out = new DataOutputStream(socket.getOutputStream());
final int nb = ((Number) nbLabels.getValue()).intValue();
for (int i = 0; i < nb; i++) {
out.write(data);
}
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(printButton, "Erreur d'impression réseau : " + ex.getMessage());
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
 
}
} else {
try {
final PrinterJob pj1 = PrinterJob.getPrinterJob();
if (pj1.printDialog()) {
final PrintService ps = pj1.getPrintService();
final DocPrintJob pj = ps.createPrintJob();
final SimpleDoc doc = new SimpleDoc(data, DocFlavor.BYTE_ARRAY.AUTOSENSE, null);
final int nb = ((Number) nbLabels.getValue()).intValue();
for (int i = 0; i < nb; i++) {
pj.print(doc, null);
Thread.sleep(((Number) delayLabels.getValue()).intValue());
}
}
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(printButton, "Erreur d'impression locale : " + ex.getMessage());
}
}
 
}
});
 
}
 
private String createZPLCode() {
 
final BufferedReader reader = new BufferedReader(new StringReader(this.zpl));
final StringBuilder builder = new StringBuilder();
 
try {
String line = reader.readLine();
while (line != null) {
if (line.contains("${")) {
boolean add = false;
for (String v : this.editorMap.keySet()) {
if (line.contains("${" + v + "}")) {
final String value = this.editorMap.get(v).getText();
line = line.replace("${" + v + "}", value);
if (!value.trim().isEmpty()) {
add = true;
}
}
}
if (add) {
builder.append(line);
builder.append("\n");
}
 
} else {
builder.append(line);
builder.append("\n");
}
line = reader.readLine();
}
 
} catch (Exception e) {
e.printStackTrace();
}
 
return builder.toString();
}
 
public String getValueAsString(SQLRowAccessor row, String variableName) {
if (row == null) {
return null;
}
if (variableName.equals("product.code")) {
return row.getString("CODE");
} else if (variableName.equals("product.name")) {
return row.getString("NOM");
} else if (variableName.equals("product.ean13")) {
return row.getString("CODE_BARRE");
} else if (variableName.equals("product.price")) {
return new DecimalFormat("#0.00").format(row.getBigDecimal("PV_HT"));
} else if (variableName.equals("product.pricewithtax")) {
return new DecimalFormat("#0.00").format(row.getBigDecimal("PV_TTC"));
} else if (variableName.equals("product.material")) {
return row.getString("MATIERE");
}
return "";
}
 
public String getName(String variableName) {
String n = mapName.get(variableName);
if (n == null) {
return variableName;
}
return n;
}
 
public List<String> getVariables(String str) {
final List<String> result = new ArrayList<>();
if (str == null || str.length() < 4) {
return result;
}
final int l = str.length() - 1;
int start = 0;
boolean inName = false;
for (int i = 0; i < l; i++) {
char c1 = str.charAt(i);
char c2 = str.charAt(i + 1);
if (!inName) {
if (c1 == '$' && c2 == '{') {
start = i + 2;
inName = true;
}
} else if (c2 == '}') {
final int stop = i + 1;
String v = str.substring(start, stop);
result.add(v);
inName = false;
}
}
return result;
}
}
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/GS1Label.java
New file
0,0 → 1,16
package org.openconcerto.modules.label;
 
import org.openconcerto.modules.label.gs1.GS1AIElements;
 
public class GS1Label extends Label {
String text;
String text2;
GS1AIElements gs1;
 
public GS1Label(String text, String text2, GS1AIElements gs1) {
this.text = text;
this.text2 = text2;
this.gs1 = gs1;
}
 
}
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/ISO646.java
New file
0,0 → 1,30
package org.openconcerto.modules.label;
 
public class ISO646 {
public static final String ALLOWED_CHARS = "!\"%&'()*+,-./01234567989:;<=>?ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";
 
public static boolean isValid(char c) {
final int length = ALLOWED_CHARS.length();
for (int i = 0; i < length; i++) {
if (c == ALLOWED_CHARS.charAt(i)) {
return true;
}
}
return false;
}
 
public static String clean(String s) {
final int length = s.length();
final StringBuilder b = new StringBuilder(length);
for (int i = 0; i < length; i++) {
final char charAt = s.charAt(i);
if (isValid(charAt)) {
b.append(s.charAt(i));
} else {
b.append('_');
}
}
return b.toString();
}
 
}
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/LabelFrame.java
20,7 → 20,6
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
 
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.utils.ExceptionHandler;
 
30,7 → 29,7
private static final int DEFAULT_COLS = 4;
final LabelPanel labelPanel;
 
public LabelFrame(List<? extends SQLRowAccessor> list, LabelRenderer labelRenderer) {
public LabelFrame(List<? extends Label> list, LabelRenderer labelRenderer) {
final JPanel p = new JPanel();
p.setLayout(new GridBagLayout());
final GridBagConstraints c = new DefaultGridBagConstraints();
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/48.png
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
/trunk/Modules/Module Label/src/org/openconcerto/modules/label/48.png
New file
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/trunk/Modules/Module Label/src/uk/org/okapibarcode/util/Doubles.java
New file
0,0 → 1,39
/*
* Copyright 2015 Daniel Gredler
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
 
package uk.org.okapibarcode.util;
 
/**
* Double utility class.
*
* @author Daniel Gredler
*/
public final class Doubles {
 
private Doubles() {
// utility class
}
 
/**
* It's usually not a good idea to check floating point numbers for exact equality. This method
* allows us to check for approximate equality.
*
* @param d1 the first double
* @param d2 the second double
* @return whether or not the two doubles are approximately equal (to within 0.0001)
*/
public static boolean roughlyEqual(final double d1, final double d2) {
return Math.abs(d1 - d2) < 0.0001;
}
}
/trunk/Modules/Module Label/src/uk/org/okapibarcode/util/Arrays.java
New file
0,0 → 1,112
/*
* Copyright 2018 Daniel Gredler
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
 
package uk.org.okapibarcode.util;
 
import uk.org.okapibarcode.backend.OkapiException;
 
/**
* Array utility class.
*
* @author Daniel Gredler
*/
public final class Arrays {
 
private Arrays() {
// utility class
}
 
/**
* Returns the position of the specified value in the specified array.
*
* @param value the value to search for
* @param array the array to search in
* @return the position of the specified value in the specified array
*/
public static int positionOf(final char value, final char[] array) {
for (int i = 0; i < array.length; i++) {
if (value == array[i]) {
return i;
}
}
throw new OkapiException("Unable to find character '" + value + "' in character array.");
}
 
/**
* Returns the position of the specified value in the specified array.
*
* @param value the value to search for
* @param array the array to search in
* @return the position of the specified value in the specified array
*/
public static int positionOf(final int value, final int[] array) {
for (int i = 0; i < array.length; i++) {
if (value == array[i]) {
return i;
}
}
throw new OkapiException("Unable to find integer '" + value + "' in integer array.");
}
 
/**
* Returns <code>true</code> if the specified array contains the specified value.
*
* @param array the array to check in
* @param value the value to check for
* @return true if the specified array contains the specified value
*/
public static boolean contains(final int[] array, final int value) {
for (int i = 0; i < array.length; i++) {
if (array[i] == value) {
return true;
}
}
return false;
}
 
/**
* Returns <code>true</code> if the specified array contains the specified sub-array at the
* specified index.
*
* @param array the array to search in
* @param searchFor the sub-array to search for
* @param index the index at which to search
* @return whether or not the specified array contains the specified sub-array at the specified
* index
*/
public static boolean containsAt(final byte[] array, final byte[] searchFor, final int index) {
for (int i = 0; i < searchFor.length; i++) {
if (index + i >= array.length || array[index + i] != searchFor[i]) {
return false;
}
}
return true;
}
 
/**
* Inserts the specified array into the specified original array at the specified index.
*
* @param original the original array into which we want to insert another array
* @param index the index at which we want to insert the array
* @param inserted the array that we want to insert
* @return the combined array
*/
public static int[] insertArray(final int[] original, final int index, final int[] inserted) {
final int[] modified = new int[original.length + inserted.length];
System.arraycopy(original, 0, modified, 0, index);
System.arraycopy(inserted, 0, modified, index, inserted.length);
System.arraycopy(original, index, modified, index + inserted.length, modified.length - index - inserted.length);
return modified;
}
}
/trunk/Modules/Module Label/src/uk/org/okapibarcode/util/EciMode.java
New file
0,0 → 1,67
/*
* Copyright 2018 Daniel Gredler
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
 
package uk.org.okapibarcode.util;
 
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
 
public class EciMode {
 
public static final EciMode NONE = new EciMode(-1, null);
 
public final int mode;
public final Charset charset;
 
private EciMode(final int mode, final Charset charset) {
this.mode = mode;
this.charset = charset;
}
 
public static EciMode of(final String data, final String charsetName, final int mode) {
try {
final Charset charset = Charset.forName(charsetName);
if (charset.canEncode() && charset.newEncoder().canEncode(data)) {
return new EciMode(mode, charset);
} else {
return NONE;
}
} catch (final UnsupportedCharsetException e) {
return NONE;
}
}
 
public EciMode or(final String data, final String charsetName, final int mode) {
if (!equals(NONE)) {
return this;
} else {
return of(data, charsetName, mode);
}
}
 
@Override
public boolean equals(final Object other) {
return other instanceof EciMode && ((EciMode) other).mode == this.mode;
}
 
@Override
public int hashCode() {
return Integer.valueOf(this.mode).hashCode();
}
 
@Override
public String toString() {
return "EciMode[mode=" + this.mode + ", charset=" + this.charset + "]";
}
}
/trunk/Modules/Module Label/src/uk/org/okapibarcode/util/Strings.java
New file
0,0 → 1,226
/*
* Copyright 2018 Daniel Gredler
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
 
package uk.org.okapibarcode.util;
 
import static java.nio.charset.StandardCharsets.ISO_8859_1;
 
import java.nio.charset.StandardCharsets;
 
import uk.org.okapibarcode.backend.OkapiException;
 
/**
* String utility class.
*
* @author Daniel Gredler
*/
public final class Strings {
 
private Strings() {
// utility class
}
 
/**
* Replaces raw values with special placeholders, where applicable.
*
* @param s the string to add placeholders to
* @return the specified string, with placeholders added
* @see <a href="http://www.zint.org.uk/Manual.aspx?type=p&page=4">Zint placeholders</a>
* @see #unescape(String, boolean)
*/
public static String escape(final String s) {
final StringBuilder sb = new StringBuilder(s.length() + 10);
for (int i = 0; i < s.length(); i++) {
final char c = s.charAt(i);
switch (c) {
case '\u0000':
sb.append("\\0"); // null
break;
case '\u0004':
sb.append("\\E"); // end of transmission
break;
case '\u0007':
sb.append("\\a"); // bell
break;
case '\u0008':
sb.append("\\b"); // backspace
break;
case '\u0009':
sb.append("\\t"); // horizontal tab
break;
case '\n':
sb.append("\\n"); // line feed
break;
case '\u000b':
sb.append("\\v"); // vertical tab
break;
case '\u000c':
sb.append("\\f"); // form feed
break;
case '\r':
sb.append("\\r"); // carriage return
break;
case '\u001b':
sb.append("\\e"); // escape
break;
case '\u001d':
sb.append("\\G"); // group separator
break;
case '\u001e':
sb.append("\\R"); // record separator
break;
case '\\':
sb.append("\\\\"); // escape the escape character
break;
default:
if (c >= 32 && c <= 126) {
sb.append(c); // printable ASCII
} else {
final byte[] bytes = String.valueOf(c).getBytes(ISO_8859_1);
final String hex = String.format("%02X", bytes[0] & 0xFF);
sb.append("\\x").append(hex);
}
break;
}
}
return sb.toString();
}
 
/**
* Replaces any special placeholders with their raw values (not including FNC values).
*
* @param s the string to check for placeholders
* @param lenient whether or not to be lenient with unrecognized escape sequences
* @return the specified string, with placeholders replaced
* @see <a href="http://www.zint.org.uk/Manual.aspx?type=p&page=4">Zint placeholders</a>
* @see #escape(String)
*/
public static String unescape(final String s, final boolean lenient) {
final StringBuilder sb = new StringBuilder(s.length());
for (int i = 0; i < s.length(); i++) {
final char c = s.charAt(i);
if (c != '\\') {
sb.append(c);
} else {
if (i + 1 >= s.length()) {
final String msg = "Error processing escape sequences: expected escape character, found end of string";
throw new OkapiException(msg);
} else {
final char c2 = s.charAt(i + 1);
switch (c2) {
case '0':
sb.append('\u0000'); // null
i++;
break;
case 'E':
sb.append('\u0004'); // end of transmission
i++;
break;
case 'a':
sb.append('\u0007'); // bell
i++;
break;
case 'b':
sb.append('\u0008'); // backspace
i++;
break;
case 't':
sb.append('\u0009'); // horizontal tab
i++;
break;
case 'n':
sb.append('\n'); // line feed
i++;
break;
case 'v':
sb.append('\u000b'); // vertical tab
i++;
break;
case 'f':
sb.append('\u000c'); // form feed
i++;
break;
case 'r':
sb.append('\r'); // carriage return
i++;
break;
case 'e':
sb.append('\u001b'); // escape
i++;
break;
case 'G':
sb.append('\u001d'); // group separator
i++;
break;
case 'R':
sb.append('\u001e'); // record separator
i++;
break;
case '\\':
sb.append('\\'); // escape the escape character
i++;
break;
case 'x':
if (i + 3 >= s.length()) {
final String msg = "Error processing escape sequences: expected hex sequence, found end of string";
throw new OkapiException(msg);
} else {
final char c3 = s.charAt(i + 2);
final char c4 = s.charAt(i + 3);
if (isHex(c3) && isHex(c4)) {
final byte b = (byte) Integer.parseInt("" + c3 + c4, 16);
sb.append(new String(new byte[] { b }, StandardCharsets.ISO_8859_1));
i += 3;
} else {
final String msg = "Error processing escape sequences: expected hex sequence, found '" + c3 + c4 + "'";
throw new OkapiException(msg);
}
}
break;
default:
if (lenient) {
sb.append(c);
} else {
throw new OkapiException("Error processing escape sequences: expected valid escape character, found '" + c2 + "'");
}
}
}
}
}
return sb.toString();
}
 
private static boolean isHex(final char c) {
return c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f';
}
 
/**
* Appends the specific integer to the specified string, in binary format, padded to the
* specified number of digits.
*
* @param s the string to append to
* @param value the value to append, in binary format
* @param digits the number of digits to pad to
*/
public static void binaryAppend(final StringBuilder s, final int value, final int digits) {
final int start = 0x01 << digits - 1;
for (int i = 0; i < digits; i++) {
if ((value & start >> i) == 0) {
s.append('0');
} else {
s.append('1');
}
}
}
}
/trunk/Modules/Module Label/src/uk/org/okapibarcode/util/Gs1.java
New file
0,0 → 1,596
/*
* Copyright 2018 Robin Stuart, Daniel Gredler
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
 
package uk.org.okapibarcode.util;
 
import uk.org.okapibarcode.backend.OkapiException;
 
/**
* GS1 utility class.
*/
public final class Gs1 {
 
private Gs1() {
// utility class
}
 
/**
* Verifies that the specified data is in good GS1 format <tt>"[AI]data"</tt> pairs, and returns
* a reduced version of the input string containing FNC1 escape sequences instead of AI
* brackets. With a few small exceptions, this code matches the Zint GS1 validation code as
* closely as possible, in order to make it easier to keep in sync.
*
* @param s the data string to verify
* @param fnc1 the string to use to represent FNC1 in the output
* @return the input data, verified and with FNC1 strings added at the appropriate positions
* @see <a href="https://sourceforge.net/p/zint/code/ci/master/tree/backend/gs1.c">Corresponding
* Zint code</a>
* @see <a href="http://www.gs1.org/docs/gsmp/barcodes/GS1_General_Specifications.pdf">GS1
* specification</a>
*/
public static String verify(final String s, final String fnc1) {
 
// Enforce compliance with GS1 General Specification
// http://www.gs1.org/docs/gsmp/barcodes/GS1_General_Specifications.pdf
 
final char[] source = s.toCharArray();
final StringBuilder reduced = new StringBuilder(source.length);
final int[] ai_value = new int[100];
final int[] ai_location = new int[100];
final int[] data_location = new int[100];
final int[] data_length = new int[100];
int error_latch;
 
/* Detect extended ASCII characters */
for (int i = 0; i < source.length; i++) {
if (source[i] >= 128) {
throw new OkapiException("Extended ASCII characters are not supported by GS1");
}
if (source[i] < 32) {
throw new OkapiException("Control characters are not supported by GS1");
}
}
 
/* Make sure we start with an AI */
if (source[0] != '[') {
throw new OkapiException("Data does not start with an AI");
}
 
/* Check the position of the brackets */
int bracket_level = 0;
int max_bracket_level = 0;
int ai_length = 0;
int max_ai_length = 0;
int min_ai_length = 5;
int j = 0;
boolean ai_latch = false;
for (int i = 0; i < source.length; i++) {
ai_length += j;
if (j == 1 && source[i] != ']' && (source[i] < '0' || source[i] > '9')) {
ai_latch = true;
}
if (source[i] == '[') {
bracket_level++;
j = 1;
}
if (source[i] == ']') {
bracket_level--;
if (ai_length < min_ai_length) {
min_ai_length = ai_length;
}
j = 0;
ai_length = 0;
}
if (bracket_level > max_bracket_level) {
max_bracket_level = bracket_level;
}
if (ai_length > max_ai_length) {
max_ai_length = ai_length;
}
}
min_ai_length--;
 
if (bracket_level != 0) {
/* Not all brackets are closed */
throw new OkapiException("Malformed AI in input data (brackets don't match)");
}
 
if (max_bracket_level > 1) {
/* Nested brackets */
throw new OkapiException("Found nested brackets in input data");
}
 
if (max_ai_length > 4) {
/* AI is too long */
throw new OkapiException("Invalid AI in input data (AI too long)");
}
 
if (min_ai_length <= 1) {
/* AI is too short */
throw new OkapiException("Invalid AI in input data (AI too short)");
}
 
if (ai_latch) {
/* Non-numeric data in AI */
throw new OkapiException("Invalid AI in input data (non-numeric characters in AI)");
}
 
int ai_count = 0;
for (int i = 1; i < source.length; i++) {
if (source[i - 1] == '[') {
ai_location[ai_count] = i;
ai_value[ai_count] = 0;
for (j = 0; source[i + j] != ']'; j++) {
ai_value[ai_count] *= 10;
ai_value[ai_count] += Character.getNumericValue(source[i + j]);
}
ai_count++;
}
}
 
for (int i = 0; i < ai_count; i++) {
data_location[i] = ai_location[i] + 3;
if (ai_value[i] >= 100) {
data_location[i]++;
}
if (ai_value[i] >= 1000) {
data_location[i]++;
}
data_length[i] = source.length - data_location[i];
for (j = source.length - 1; j >= data_location[i]; j--) {
if (source[j] == '[') {
data_length[i] = j - data_location[i];
}
}
}
 
for (int i = 0; i < ai_count; i++) {
if (data_length[i] == 0) {
/* No data for given AI */
throw new OkapiException("Empty data field in input data");
}
}
 
// Check for valid AI values and data lengths according to GS1 General
// Specification Release 18, January 2018
for (int i = 0; i < ai_count; i++) {
 
error_latch = 2;
switch (ai_value[i]) {
// Length 2 Fixed
case 20: // VARIANT
if (data_length[i] != 2) {
error_latch = 1;
} else {
error_latch = 0;
}
break;
 
// Length 3 Fixed
case 422: // ORIGIN
case 424: // COUNTRY PROCESS
case 426: // COUNTRY FULL PROCESS
if (data_length[i] != 3) {
error_latch = 1;
} else {
error_latch = 0;
}
break;
 
// Length 4 Fixed
case 8111: // POINTS
if (data_length[i] != 4) {
error_latch = 1;
} else {
error_latch = 0;
}
break;
 
// Length 6 Fixed
case 11: // PROD DATE
case 12: // DUE DATE
case 13: // PACK DATE
case 15: // BEST BY
case 16: // SELL BY
case 17: // USE BY
case 7006: // FIRST FREEZE DATE
case 8005: // PRICE PER UNIT
if (data_length[i] != 6) {
error_latch = 1;
} else {
error_latch = 0;
}
break;
 
// Length 10 Fixed
case 7003: // EXPIRY TIME
if (data_length[i] != 10) {
error_latch = 1;
} else {
error_latch = 0;
}
break;
 
// Length 13 Fixed
case 410: // SHIP TO LOC
case 411: // BILL TO
case 412: // PURCHASE FROM
case 413: // SHIP FOR LOC
case 414: // LOC NO
case 415: // PAY TO
case 416: // PROD/SERV LOC
case 7001: // NSN
if (data_length[i] != 13) {
error_latch = 1;
} else {
error_latch = 0;
}
break;
 
// Length 14 Fixed
case 1: // GTIN
case 2: // CONTENT
case 8001: // DIMENSIONS
if (data_length[i] != 14) {
error_latch = 1;
} else {
error_latch = 0;
}
break;
 
// Length 17 Fixed
case 402: // GSIN
if (data_length[i] != 17) {
error_latch = 1;
} else {
error_latch = 0;
}
break;
 
// Length 18 Fixed
case 0: // SSCC
case 8006: // ITIP
case 8017: // GSRN PROVIDER
case 8018: // GSRN RECIPIENT
if (data_length[i] != 18) {
error_latch = 1;
} else {
error_latch = 0;
}
break;
 
// Length 2 Max
case 7010: // PROD METHOD
if (data_length[i] > 2) {
error_latch = 1;
} else {
error_latch = 0;
}
break;
 
// Length 3 Max
case 427: // ORIGIN SUBDIVISION
case 7008: // AQUATIC SPECIES
if (data_length[i] > 3) {
error_latch = 1;
} else {
error_latch = 0;
}
break;
 
// Length 4 Max
case 7004: // ACTIVE POTENCY
if (data_length[i] > 4) {
error_latch = 1;
} else {
error_latch = 0;
}
break;
 
// Length 6 Max
case 242: // MTO VARIANT
if (data_length[i] > 6) {
error_latch = 1;
} else {
error_latch = 0;
}
break;
 
// Length 8 Max
case 30: // VAR COUNT
case 37: // COUNT
if (data_length[i] > 8) {
error_latch = 1;
} else {
error_latch = 0;
}
break;
 
// Length 10 Max
case 7009: // FISHING GEAR TYPE
case 8019: // SRIN
if (data_length[i] > 10) {
error_latch = 1;
} else {
error_latch = 0;
}
break;
 
// Length 12 Max
case 7005: // CATCH AREA
case 8011: // CPID SERIAL
if (data_length[i] > 12) {
error_latch = 1;
} else {
error_latch = 0;
}
break;
 
// Length 20 Max
case 10: // BATCH/LOT
case 21: // SERIAL
case 22: // CPV
case 243: // PCN
case 254: // GLN EXTENSION COMPONENT
case 420: // SHIP TO POST
case 7020: // REFURB LOT
case 7021: // FUNC STAT
case 7022: // REV STAT
case 710: // NHRN PZN
case 711: // NHRN CIP
case 712: // NHRN CN
case 713: // NHRN DRN
case 714: // NHRN AIM
case 8002: // CMT NO
case 8012: // VERSION
if (data_length[i] > 20) {
error_latch = 1;
} else {
error_latch = 0;
}
break;
 
// Length 25 Max
case 8020: // REF NO
if (data_length[i] > 25) {
error_latch = 1;
} else {
error_latch = 0;
}
break;
 
// Length 30 Max
case 240: // ADDITIONAL ID
case 241: // CUST PART NO
case 250: // SECONDARY SERIAL
case 251: // REF TO SOURCE
case 400: // ORDER NUMBER
case 401: // GINC
case 403: // ROUTE
case 7002: // MEAT CUT
case 7023: // GIAI ASSEMBLY
case 8004: // GIAI
case 8010: // CPID
case 8013: // BUDI-DI
case 90: // INTERNAL
if (data_length[i] > 30) {
error_latch = 1;
} else {
error_latch = 0;
}
break;
 
// Length 34 Max
case 8007: // IBAN
if (data_length[i] > 34) {
error_latch = 1;
} else {
error_latch = 0;
}
break;
 
// Length 70 Max
case 8110: // Coupon code
case 8112: // Paperless coupon code
case 8200: // PRODUCT URL
if (data_length[i] > 70) {
error_latch = 1;
} else {
error_latch = 0;
}
break;
 
}
 
if (ai_value[i] == 253) { // GDTI
if (data_length[i] < 14 || data_length[i] > 30) {
error_latch = 1;
} else {
error_latch = 0;
}
}
 
if (ai_value[i] == 255) { // GCN
if (data_length[i] < 14 || data_length[i] > 25) {
error_latch = 1;
} else {
error_latch = 0;
}
}
 
if (ai_value[i] >= 3100 && ai_value[i] <= 3169) {
if (data_length[i] != 6) {
error_latch = 1;
} else {
error_latch = 0;
}
}
 
if (ai_value[i] >= 3200 && ai_value[i] <= 3379) {
if (data_length[i] != 6) {
error_latch = 1;
} else {
error_latch = 0;
}
}
 
if (ai_value[i] >= 3400 && ai_value[i] <= 3579) {
if (data_length[i] != 6) {
error_latch = 1;
} else {
error_latch = 0;
}
}
 
if (ai_value[i] >= 3600 && ai_value[i] <= 3699) {
if (data_length[i] != 6) {
error_latch = 1;
} else {
error_latch = 0;
}
}
 
if (ai_value[i] >= 3900 && ai_value[i] <= 3909) { // AMOUNT
if (data_length[i] > 15) {
error_latch = 1;
} else {
error_latch = 0;
}
}
 
if (ai_value[i] >= 3910 && ai_value[i] <= 3919) { // AMOUNT
if (data_length[i] < 4 || data_length[i] > 18) {
error_latch = 1;
} else {
error_latch = 0;
}
}
 
if (ai_value[i] >= 3920 && ai_value[i] <= 3929) { // PRICE
if (data_length[i] > 15) {
error_latch = 1;
} else {
error_latch = 0;
}
}
 
if (ai_value[i] >= 3930 && ai_value[i] <= 3939) { // PRICE
if (data_length[i] < 4 || data_length[i] > 18) {
error_latch = 1;
} else {
error_latch = 0;
}
}
 
if (ai_value[i] >= 3940 && ai_value[i] <= 3949) { // PRCNT OFF
if (data_length[i] != 4) {
error_latch = 1;
} else {
error_latch = 0;
}
}
 
if (ai_value[i] == 421) { // SHIP TO POST
if (data_length[i] < 3 || data_length[i] > 12) {
error_latch = 1;
} else {
error_latch = 0;
}
}
 
if (ai_value[i] == 423 || ai_value[i] == 425) {
// COUNTRY INITIAL PROCESS || COUNTRY DISASSEMBLY
if (data_length[i] < 3 || data_length[i] > 15) {
error_latch = 1;
} else {
error_latch = 0;
}
}
 
if (ai_value[i] == 7007) { // HARVEST DATE
if (data_length[i] < 6 || data_length[i] > 12) {
error_latch = 1;
} else {
error_latch = 0;
}
}
 
if (ai_value[i] >= 7030 && ai_value[i] <= 7039) { // PROCESSOR #
if (data_length[i] < 4 || data_length[i] > 30) {
error_latch = 1;
} else {
error_latch = 0;
}
}
 
if (ai_value[i] == 8003) { // GRAI
if (data_length[i] < 15 || data_length[i] > 30) {
error_latch = 1;
} else {
error_latch = 0;
}
}
 
if (ai_value[i] == 8008) { // PROD TIME
if (data_length[i] < 9 || data_length[i] > 12) {
error_latch = 1;
} else {
error_latch = 0;
}
}
 
if (ai_value[i] >= 91 && ai_value[i] <= 99) { // INTERNAL
if (data_length[i] > 90) {
error_latch = 1;
} else {
error_latch = 0;
}
}
 
if (error_latch == 1) {
throw new OkapiException("Invalid data length for AI");
}
 
if (error_latch == 2) {
throw new OkapiException("Invalid AI value");
}
}
 
/* Resolve AI data - put resulting string in 'reduced' */
int last_ai = 0;
boolean fixedLengthAI = true;
for (int i = 0; i < source.length; i++) {
if (source[i] != '[' && source[i] != ']') {
reduced.append(source[i]);
}
if (source[i] == '[') {
/* Start of an AI string */
if (!fixedLengthAI) {
reduced.append(fnc1);
}
last_ai = 10 * Character.getNumericValue(source[i + 1]) + Character.getNumericValue(source[i + 2]);
/*
* The following values from
* "GS-1 General Specification version 8.0 issue 2, May 2008" figure 5.4.8.2.1 - 1
* "Element Strings with Pre-Defined Length Using Application Identifiers"
*/
fixedLengthAI = last_ai >= 0 && last_ai <= 4 || last_ai >= 11 && last_ai <= 20 || last_ai == 23
|| /* legacy support - see 5.3.8.2.2 */
last_ai >= 31 && last_ai <= 36 || last_ai == 41;
}
}
 
return reduced.toString();
}
}
/trunk/Modules/Module Label/src/uk/org/okapibarcode/output/PostScriptRenderer.java
New file
0,0 → 1,211
/*
* Copyright 2015 Robin Stuart, Daniel Gredler
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
 
package uk.org.okapibarcode.output;
 
import static uk.org.okapibarcode.backend.HumanReadableAlignment.CENTER;
import static uk.org.okapibarcode.backend.HumanReadableAlignment.JUSTIFY;
import static uk.org.okapibarcode.util.Doubles.roughlyEqual;
 
import java.awt.Color;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.OutputStream;
 
import uk.org.okapibarcode.backend.Hexagon;
import uk.org.okapibarcode.backend.HumanReadableAlignment;
import uk.org.okapibarcode.backend.Symbol;
import uk.org.okapibarcode.backend.TextBox;
 
/**
* Renders symbologies to EPS (Encapsulated PostScript).
*
* @author <a href="mailto:rstuart114@gmail.com">Robin Stuart</a>
* @author Daniel Gredler
*/
public class PostScriptRenderer implements SymbolRenderer {
 
/** The output stream to render to. */
private final OutputStream out;
 
/** The magnification factor to apply. */
private final double magnification;
 
/** The paper (background) color. */
private final Color paper;
 
/** The ink (foreground) color. */
private final Color ink;
 
/**
* Creates a new PostScript renderer.
*
* @param out the output stream to render to
* @param magnification the magnification factor to apply
* @param paper the paper (background) color
* @param ink the ink (foreground) color
*/
public PostScriptRenderer(final OutputStream out, final double magnification, final Color paper, final Color ink) {
this.out = out;
this.magnification = magnification;
this.paper = paper;
this.ink = ink;
}
 
/** {@inheritDoc} */
@Override
public void render(final Symbol symbol) throws IOException {
 
// All y dimensions are reversed because EPS origin (0,0) is at the bottom left, not top
// left
 
final String content = symbol.getContent();
final int width = (int) (symbol.getWidth() * this.magnification);
final int height = (int) (symbol.getHeight() * this.magnification);
final int marginX = (int) (symbol.getQuietZoneHorizontal() * this.magnification);
final int marginY = (int) (symbol.getQuietZoneVertical() * this.magnification);
 
String title;
if (content == null || content.isEmpty()) {
title = "OkapiBarcode Generated Symbol";
} else {
title = content;
}
 
try (ExtendedOutputStreamWriter writer = new ExtendedOutputStreamWriter(this.out, "%.2f")) {
 
// Header
writer.append("%!PS-Adobe-3.0 EPSF-3.0\n");
writer.append("%%Creator: OkapiBarcode\n");
writer.append("%%Title: ").append(title).append('\n');
writer.append("%%Pages: 0\n");
writer.append("%%BoundingBox: 0 0 ").appendInt(width).append(" ").appendInt(height).append("\n");
writer.append("%%EndComments\n");
 
// Definitions
writer.append("/TL { setlinewidth moveto lineto stroke } bind def\n");
writer.append("/TC { moveto 0 360 arc 360 0 arcn fill } bind def\n");
writer.append("/TH { 0 setlinewidth moveto lineto lineto lineto lineto lineto closepath fill } bind def\n");
writer.append("/TB { 2 copy } bind def\n");
writer.append("/TR { newpath 4 1 roll exch moveto 1 index 0 rlineto 0 exch rlineto neg 0 rlineto closepath fill } bind def\n");
writer.append("/TE { pop pop } bind def\n");
 
// Background
writer.append("newpath\n");
writer.append(this.ink.getRed() / 255.0).append(" ").append(this.ink.getGreen() / 255.0).append(" ").append(this.ink.getBlue() / 255.0).append(" setrgbcolor\n");
writer.append(this.paper.getRed() / 255.0).append(" ").append(this.paper.getGreen() / 255.0).append(" ").append(this.paper.getBlue() / 255.0).append(" setrgbcolor\n");
writer.append(height).append(" 0.00 TB 0.00 ").append(width).append(" TR\n");
 
// Rectangles
for (int i = 0; i < symbol.getRectangles().size(); i++) {
final Rectangle2D.Double rect = symbol.getRectangles().get(i);
if (i == 0) {
writer.append("TE\n");
writer.append(this.ink.getRed() / 255.0).append(" ").append(this.ink.getGreen() / 255.0).append(" ").append(this.ink.getBlue() / 255.0).append(" setrgbcolor\n");
writer.append(rect.height * this.magnification).append(" ").append(height - (rect.y + rect.height) * this.magnification - marginY).append(" TB ")
.append(rect.x * this.magnification + marginX).append(" ").append(rect.width * this.magnification).append(" TR\n");
} else {
final Rectangle2D.Double prev = symbol.getRectangles().get(i - 1);
if (!roughlyEqual(rect.height, prev.height) || !roughlyEqual(rect.y, prev.y)) {
writer.append("TE\n");
writer.append(this.ink.getRed() / 255.0).append(" ").append(this.ink.getGreen() / 255.0).append(" ").append(this.ink.getBlue() / 255.0).append(" setrgbcolor\n");
writer.append(rect.height * this.magnification).append(" ").append(height - (rect.y + rect.height) * this.magnification - marginY).append(" ");
}
writer.append("TB ").append(rect.x * this.magnification + marginX).append(" ").append(rect.width * this.magnification).append(" TR\n");
}
}
 
// Text
for (int i = 0; i < symbol.getTexts().size(); i++) {
final TextBox text = symbol.getTexts().get(i);
final HumanReadableAlignment alignment = text.alignment == JUSTIFY && text.text.length() == 1 ? CENTER : text.alignment;
if (i == 0) {
writer.append("TE\n");
;
writer.append(this.ink.getRed() / 255.0).append(" ").append(this.ink.getGreen() / 255.0).append(" ").append(this.ink.getBlue() / 255.0).append(" setrgbcolor\n");
}
writer.append("matrix currentmatrix\n");
writer.append("/").append(symbol.getFontName()).append(" findfont\n");
writer.append(symbol.getFontSize() * this.magnification).append(" scalefont setfont\n");
final double y = height - text.y * this.magnification - marginY;
switch (alignment) {
case LEFT:
final double leftX = this.magnification * text.x + marginX;
writer.append(" 0 0 moveto ").append(leftX).append(" ").append(y).append(" translate 0.00 rotate 0 0 moveto\n");
writer.append(" (").append(text.text).append(") show\n");
break;
case JUSTIFY:
final double textX = this.magnification * text.x + marginX;
final double textW = this.magnification * text.width;
writer.append(" 0 0 moveto ").append(textX).append(" ").append(y).append(" translate 0.00 rotate 0 0 moveto\n");
writer.append(" (").append(text.text).append(") dup stringwidth pop ").append(textW).append(" sub neg 1 index length 1 sub div 0").append(" 3 -1 roll ashow\n");
break;
case RIGHT:
final double rightX = this.magnification * text.x + this.magnification * text.width + marginX;
writer.append(" 0 0 moveto ").append(rightX).append(" ").append(y).append(" translate 0.00 rotate 0 0 moveto\n");
writer.append(" (").append(text.text).append(") stringwidth\n");
writer.append("pop\n");
writer.append("-1 mul 0 rmoveto\n");
writer.append(" (").append(text.text).append(") show\n");
break;
case CENTER:
final double centerX = this.magnification * text.x + this.magnification * text.width / 2 + marginX;
writer.append(" 0 0 moveto ").append(centerX).append(" ").append(y).append(" translate 0.00 rotate 0 0 moveto\n");
writer.append(" (").append(text.text).append(") stringwidth\n");
writer.append("pop\n");
writer.append("-2 div 0 rmoveto\n");
writer.append(" (").append(text.text).append(") show\n");
break;
default:
throw new IllegalStateException("Unknown alignment: " + alignment);
}
writer.append("setmatrix\n");
}
 
// Circles
// Because MaxiCode size is fixed, this ignores magnification
for (int i = 0; i < symbol.getTarget().size(); i += 2) {
final Ellipse2D.Double ellipse1 = symbol.getTarget().get(i);
final Ellipse2D.Double ellipse2 = symbol.getTarget().get(i + 1);
if (i == 0) {
writer.append("TE\n");
writer.append(this.ink.getRed() / 255.0).append(" ").append(this.ink.getGreen() / 255.0).append(" ").append(this.ink.getBlue() / 255.0).append(" setrgbcolor\n");
writer.append(this.ink.getRed() / 255.0).append(" ").append(this.ink.getGreen() / 255.0).append(" ").append(this.ink.getBlue() / 255.0).append(" setrgbcolor\n");
}
final double x1 = ellipse1.x + ellipse1.width / 2;
final double x2 = ellipse2.x + ellipse2.width / 2;
final double y1 = height - ellipse1.y - ellipse1.width / 2;
final double y2 = height - ellipse2.y - ellipse2.width / 2;
final double r1 = ellipse1.width / 2;
final double r2 = ellipse2.width / 2;
writer.append(x1 + marginX).append(" ").append(y1 - marginY).append(" ").append(r1).append(" ").append(x2 + marginX).append(" ").append(y2 - marginY).append(" ").append(r2).append(" ")
.append(x2 + r2 + marginX).append(" ").append(y2 - marginY).append(" TC\n");
}
 
// Hexagons
// Because MaxiCode size is fixed, this ignores magnification
for (int i = 0; i < symbol.getHexagons().size(); i++) {
final Hexagon hexagon = symbol.getHexagons().get(i);
for (int j = 0; j < 6; j++) {
writer.append(hexagon.pointX[j] + marginX).append(" ").append(height - hexagon.pointY[j] - marginY).append(" ");
}
writer.append(" TH\n");
}
 
// Footer
writer.append("\nshowpage\n");
}
}
}
/trunk/Modules/Module Label/src/uk/org/okapibarcode/output/SvgRenderer.java
New file
0,0 → 1,225
/*
* Copyright 2014-2015 Robin Stuart, Daniel Gredler
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
 
package uk.org.okapibarcode.output;
 
import static uk.org.okapibarcode.backend.HumanReadableAlignment.CENTER;
import static uk.org.okapibarcode.backend.HumanReadableAlignment.JUSTIFY;
 
import java.awt.Color;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
 
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
 
import org.w3c.dom.Document;
import org.w3c.dom.Text;
 
import uk.org.okapibarcode.backend.Hexagon;
import uk.org.okapibarcode.backend.HumanReadableAlignment;
import uk.org.okapibarcode.backend.Symbol;
import uk.org.okapibarcode.backend.TextBox;
 
/**
* Renders symbologies to SVG (Scalable Vector Graphics).
*
* @author <a href="mailto:rstuart114@gmail.com">Robin Stuart</a>
* @author Daniel Gredler
*/
public class SvgRenderer implements SymbolRenderer {
 
/** The output stream to render to. */
private final OutputStream out;
 
/** The magnification factor to apply. */
private final double magnification;
 
/** The paper (background) color. */
private final Color paper;
 
/** The ink (foreground) color. */
private final Color ink;
 
/** Whether or not to include the XML prolog in the output. */
private final boolean xmlProlog;
 
/**
* Creates a new SVG renderer.
*
* @param out the output stream to render to
* @param magnification the magnification factor to apply
* @param paper the paper (background) color
* @param ink the ink (foreground) color
* @param xmlProlog whether or not to include the XML prolog in the output (usually {@code true}
* for standalone SVG documents, {@code false} for SVG content embedded directly in HTML
* documents)
*/
public SvgRenderer(final OutputStream out, final double magnification, final Color paper, final Color ink, final boolean xmlProlog) {
this.out = out;
this.magnification = magnification;
this.paper = paper;
this.ink = ink;
this.xmlProlog = xmlProlog;
}
 
/** {@inheritDoc} */
@Override
public void render(final Symbol symbol) throws IOException {
 
final String content = symbol.getContent();
final int width = (int) (symbol.getWidth() * this.magnification);
final int height = (int) (symbol.getHeight() * this.magnification);
final int marginX = (int) (symbol.getQuietZoneHorizontal() * this.magnification);
final int marginY = (int) (symbol.getQuietZoneVertical() * this.magnification);
 
String title;
if (content == null || content.isEmpty()) {
title = "OkapiBarcode Generated Symbol";
} else {
title = content;
}
 
final String fgColour = String.format("%02X", this.ink.getRed()) + String.format("%02X", this.ink.getGreen()) + String.format("%02X", this.ink.getBlue());
 
final String bgColour = String.format("%02X", this.paper.getRed()) + String.format("%02X", this.paper.getGreen()) + String.format("%02X", this.paper.getBlue());
 
try (ExtendedOutputStreamWriter writer = new ExtendedOutputStreamWriter(this.out, "%.2f")) {
 
// XML Prolog
if (this.xmlProlog) {
writer.append("<?xml version=\"1.0\" standalone=\"no\"?>\n");
writer.append("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\n");
writer.append(" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n");
}
 
// Header
writer.append("<svg width=\"").appendInt(width).append("\" height=\"").appendInt(height).append("\" version=\"1.1").append("\" xmlns=\"http://www.w3.org/2000/svg\">\n");
writer.append(" <desc>").append(clean(title)).append("</desc>\n");
writer.append(" <g id=\"barcode\" fill=\"#").append(fgColour).append("\">\n");
writer.append(" <rect x=\"0\" y=\"0\" width=\"").appendInt(width).append("\" height=\"").appendInt(height).append("\" fill=\"#").append(bgColour).append("\" />\n");
 
// Rectangles
for (int i = 0; i < symbol.getRectangles().size(); i++) {
final Rectangle2D.Double rect = symbol.getRectangles().get(i);
writer.append(" <rect x=\"").append(rect.x * this.magnification + marginX).append("\" y=\"").append(rect.y * this.magnification + marginY).append("\" width=\"")
.append(rect.width * this.magnification).append("\" height=\"").append(rect.height * this.magnification).append("\" />\n");
}
 
// Text
for (int i = 0; i < symbol.getTexts().size(); i++) {
final TextBox text = symbol.getTexts().get(i);
final HumanReadableAlignment alignment = text.alignment == JUSTIFY && text.text.length() == 1 ? CENTER : text.alignment;
double x;
String anchor;
switch (alignment) {
case LEFT:
case JUSTIFY:
x = this.magnification * text.x + marginX;
anchor = "start";
break;
case RIGHT:
x = this.magnification * text.x + this.magnification * text.width + marginX;
anchor = "end";
break;
case CENTER:
x = this.magnification * text.x + this.magnification * text.width / 2 + marginX;
anchor = "middle";
break;
default:
throw new IllegalStateException("Unknown alignment: " + alignment);
}
writer.append(" <text x=\"").append(x).append("\" y=\"").append(text.y * this.magnification + marginY).append("\" text-anchor=\"").append(anchor).append("\"\n");
if (alignment == JUSTIFY) {
writer.append(" textLength=\"").append(text.width * this.magnification).append("\" lengthAdjust=\"spacing\"\n");
}
writer.append(" font-family=\"").append(clean(symbol.getFontName())).append("\" font-size=\"").append(symbol.getFontSize() * this.magnification).append("\" fill=\"#")
.append(fgColour).append("\">\n");
writer.append(" ").append(clean(text.text)).append("\n");
writer.append(" </text>\n");
}
 
// Circles
for (int i = 0; i < symbol.getTarget().size(); i++) {
final Ellipse2D.Double ellipse = symbol.getTarget().get(i);
String color;
if ((i & 1) == 0) {
color = fgColour;
} else {
color = bgColour;
}
writer.append(" <circle cx=\"").append((ellipse.x + ellipse.width / 2) * this.magnification + marginX).append("\" cy=\"")
.append((ellipse.y + ellipse.width / 2) * this.magnification + marginY).append("\" r=\"").append(ellipse.width / 2 * this.magnification).append("\" fill=\"#").append(color)
.append("\" />\n");
}
 
// Hexagons
for (int i = 0; i < symbol.getHexagons().size(); i++) {
final Hexagon hexagon = symbol.getHexagons().get(i);
writer.append(" <path d=\"");
for (int j = 0; j < 6; j++) {
if (j == 0) {
writer.append("M ");
} else {
writer.append("L ");
}
writer.append(hexagon.pointX[j] * this.magnification + marginX).append(" ").append(hexagon.pointY[j] * this.magnification + marginY).append(" ");
}
writer.append("Z\" />\n");
}
 
// Footer
writer.append(" </g>\n");
writer.append("</svg>\n");
}
}
 
/**
* Cleans / sanitizes the specified string for inclusion in XML. A bit convoluted, but we're
* trying to do it without adding an external dependency just for this...
*
* @param s the string to be cleaned / sanitized
* @return the cleaned / sanitized string
*/
protected String clean(String s) {
 
// remove control characters
s = s.replaceAll("[\u0000-\u001f]", "");
 
// escape XML characters
try {
final Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
final Text text = document.createTextNode(s);
final Transformer transformer = TransformerFactory.newInstance().newTransformer();
final DOMSource source = new DOMSource(text);
final StringWriter writer = new StringWriter();
final StreamResult result = new StreamResult(writer);
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.transform(source, result);
return writer.toString();
} catch (ParserConfigurationException | TransformerException | TransformerFactoryConfigurationError e) {
return s;
}
}
}
/trunk/Modules/Module Label/src/uk/org/okapibarcode/output/ExtendedOutputStreamWriter.java
New file
0,0 → 1,80
/*
* Copyright 2015 Daniel Gredler
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
 
package uk.org.okapibarcode.output;
 
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
 
/**
* {@link OutputStreamWriter} extension which provides some convenience methods for writing numbers.
*/
class ExtendedOutputStreamWriter extends OutputStreamWriter {
 
/** Format to use when writing doubles to the stream. */
private final String doubleFormat;
 
/**
* Creates a new extended output stream writer, using the UTF-8 charset.
*
* @param out the stream to write to
* @param doubleFormat the format to use when writing doubles to the stream
*/
public ExtendedOutputStreamWriter(final OutputStream out, final String doubleFormat) {
super(out, StandardCharsets.UTF_8);
this.doubleFormat = doubleFormat;
}
 
/** {@inheritDoc} */
@Override
public ExtendedOutputStreamWriter append(final CharSequence cs) throws IOException {
super.append(cs);
return this;
}
 
/** {@inheritDoc} */
@Override
public ExtendedOutputStreamWriter append(final CharSequence cs, final int start, final int end) throws IOException {
super.append(cs, start, end);
return this;
}
 
/**
* Writes the specified double to the stream, formatted according to the format specified in the
* constructor.
*
* @param d the double to write to the stream
* @return this writer
* @throws IOException if an I/O error occurs
*/
public ExtendedOutputStreamWriter append(final double d) throws IOException {
super.append(String.format(Locale.ROOT, this.doubleFormat, d));
return this;
}
 
/**
* Writes the specified integer to the stream.
*
* @param i the integer to write to the stream
* @return this writer
* @throws IOException if an I/O error occurs
*/
public ExtendedOutputStreamWriter appendInt(final int i) throws IOException {
super.append(String.valueOf(i));
return this;
}
}
/trunk/Modules/Module Label/src/uk/org/okapibarcode/output/SymbolRenderer.java
New file
0,0 → 1,34
/*
* Copyright 2015 Daniel Gredler
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
 
package uk.org.okapibarcode.output;
 
import java.io.IOException;
 
import uk.org.okapibarcode.backend.Symbol;
 
/**
* Renders symbols to some output format.
*/
public interface SymbolRenderer {
 
/**
* Renders the specified symbology.
*
* @param symbol the symbology to render
* @throws IOException if there is an I/O error
*/
void render(Symbol symbol) throws IOException;
 
}
/trunk/Modules/Module Label/src/uk/org/okapibarcode/output/Java2DRenderer.java
New file
0,0 → 1,169
/*
* Copyright 2014-2015 Robin Stuart, Robert Elliott, Daniel Gredler
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
 
package uk.org.okapibarcode.output;
 
import static uk.org.okapibarcode.backend.HumanReadableAlignment.CENTER;
import static uk.org.okapibarcode.backend.HumanReadableAlignment.JUSTIFY;
 
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.font.FontRenderContext;
import java.awt.font.TextAttribute;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.util.Collections;
import java.util.List;
 
import uk.org.okapibarcode.backend.Hexagon;
import uk.org.okapibarcode.backend.HumanReadableAlignment;
import uk.org.okapibarcode.backend.Symbol;
import uk.org.okapibarcode.backend.TextBox;
 
/**
* Renders symbologies using the Java 2D API.
*/
public class Java2DRenderer implements SymbolRenderer {
 
/** The graphics to render to. */
private final Graphics2D g2d;
 
/** The magnification factor to apply. */
private final double magnification;
 
/** The paper (background) color. */
private final Color paper;
 
/** The ink (foreground) color. */
private final Color ink;
 
/**
* Creates a new Java 2D renderer. If the specified paper color is <tt>null</tt>, the symbol is
* drawn without clearing the existing <tt>g2d</tt> background.
*
* @param g2d the graphics to render to
* @param magnification the magnification factor to apply
* @param paper the paper (background) color (may be <tt>null</tt>)
* @param ink the ink (foreground) color
*/
public Java2DRenderer(final Graphics2D g2d, final double magnification, final Color paper, final Color ink) {
this.g2d = g2d;
this.magnification = magnification;
this.paper = paper;
this.ink = ink;
}
 
/** {@inheritDoc} */
@Override
public void render(final Symbol symbol) {
 
final int marginX = (int) (symbol.getQuietZoneHorizontal() * this.magnification);
final int marginY = (int) (symbol.getQuietZoneVertical() * this.magnification);
 
Font f = symbol.getFont();
if (f != null) {
f = f.deriveFont((float) (f.getSize2D() * this.magnification));
} else {
f = new Font(symbol.getFontName(), Font.PLAIN, (int) (symbol.getFontSize() * this.magnification));
f = f.deriveFont(Collections.singletonMap(TextAttribute.TRACKING, 0));
}
 
final Font oldFont = this.g2d.getFont();
final Color oldColor = this.g2d.getColor();
 
if (this.paper != null) {
final int w = (int) (symbol.getWidth() * this.magnification);
final int h = (int) (symbol.getHeight() * this.magnification);
this.g2d.setColor(this.paper);
this.g2d.fillRect(0, 0, w, h);
}
 
this.g2d.setColor(this.ink);
 
for (final Rectangle2D.Double rect : symbol.getRectangles()) {
final double x = rect.x * this.magnification + marginX;
final double y = rect.y * this.magnification + marginY;
final double w = rect.width * this.magnification;
final double h = rect.height * this.magnification;
this.g2d.fillRect((int) x, (int) y, (int) w, (int) h);
}
 
for (final TextBox text : symbol.getTexts()) {
final HumanReadableAlignment alignment = text.alignment == JUSTIFY && text.text.length() == 1 ? CENTER : text.alignment;
final Font font = alignment != JUSTIFY ? f : addTracking(f, text.width * this.magnification, text.text, this.g2d);
this.g2d.setFont(font);
final FontMetrics fm = this.g2d.getFontMetrics();
final Rectangle2D bounds = fm.getStringBounds(text.text, this.g2d);
final float y = (float) (text.y * this.magnification) + marginY;
float x;
switch (alignment) {
case LEFT:
case JUSTIFY:
x = (float) (this.magnification * text.x + marginX);
break;
case RIGHT:
x = (float) (this.magnification * text.x + this.magnification * text.width - bounds.getWidth() + marginX);
break;
case CENTER:
x = (float) (this.magnification * text.x + this.magnification * text.width / 2 - bounds.getWidth() / 2 + marginX);
break;
default:
throw new IllegalStateException("Unknown alignment: " + alignment);
}
this.g2d.drawString(text.text, x, y);
}
 
for (final Hexagon hexagon : symbol.getHexagons()) {
final Polygon polygon = new Polygon();
for (int j = 0; j < 6; j++) {
polygon.addPoint((int) (hexagon.pointX[j] * this.magnification + marginX), (int) (hexagon.pointY[j] * this.magnification + marginY));
}
this.g2d.fill(polygon);
}
 
final List<Ellipse2D.Double> target = symbol.getTarget();
for (int i = 0; i + 1 < target.size(); i += 2) {
final Ellipse2D.Double outer = adjust(target.get(i), this.magnification, marginX, marginY);
final Ellipse2D.Double inner = adjust(target.get(i + 1), this.magnification, marginX, marginY);
final Area area = new Area(outer);
area.subtract(new Area(inner));
this.g2d.fill(area);
}
 
this.g2d.setFont(oldFont);
this.g2d.setColor(oldColor);
}
 
private static Ellipse2D.Double adjust(final Ellipse2D.Double ellipse, final double magnification, final int marginX, final int marginY) {
final double x = ellipse.x * magnification + marginX;
final double y = ellipse.y * magnification + marginY;
final double w = ellipse.width * magnification + marginX;
final double h = ellipse.height * magnification + marginY;
return new Ellipse2D.Double(x, y, w, h);
}
 
private static Font addTracking(final Font baseFont, final double maxTextWidth, final String text, final Graphics2D g2d) {
final FontRenderContext frc = g2d.getFontRenderContext();
final double originalWidth = baseFont.getStringBounds(text, frc).getWidth();
final double extraSpace = maxTextWidth - originalWidth;
final double extraSpacePerGap = extraSpace / (text.length() - 1);
final double scaleX = baseFont.isTransformed() ? baseFont.getTransform().getScaleX() : 1;
final double tracking = extraSpacePerGap / (baseFont.getSize2D() * scaleX);
return baseFont.deriveFont(Collections.singletonMap(TextAttribute.TRACKING, tracking));
}
}
/trunk/Modules/Module Label/src/uk/org/okapibarcode/backend/UspsOneCode.java
New file
0,0 → 1,458
/*
* Copyright 2014 Robin Stuart
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package uk.org.okapibarcode.backend;
 
import static uk.org.okapibarcode.backend.HumanReadableLocation.NONE;
import static uk.org.okapibarcode.backend.HumanReadableLocation.TOP;
 
import java.awt.geom.Rectangle2D;
import java.math.BigInteger;
 
/**
* <p>
* Implements USPS OneCode (also known as Intelligent Mail Barcode) according to USPS-B-3200F.
*
* <p>
* OneCode is a fixed length (65-bar) symbol which combines routing and customer information in a
* single symbol. Input data consists of a 20 digit tracking code, followed by a dash (-), followed
* by a delivery point ZIP code which can be 0, 5, 9 or 11 digits in length.
*
* @author <a href="mailto:rstuart114@gmail.com">Robin Stuart</a>
* @see <a href=
* "https://ribbs.usps.gov/intelligentmail_mailpieces/documents/tech_guides/SPUSPSG.pdf">USPS
* OneCode Specification</a>
*/
public class UspsOneCode extends Symbol {
 
/* The following lookup tables were generated using the code in Appendix C */
 
/** Appendix D Table 1 - 5 of 13 characters */
private static final int[] APPX_D_I = { 0x001F, 0x1F00, 0x002F, 0x1E80, 0x0037, 0x1D80, 0x003B, 0x1B80, 0x003D, 0x1780, 0x003E, 0x0F80, 0x004F, 0x1E40, 0x0057, 0x1D40, 0x005B, 0x1B40, 0x005D,
0x1740, 0x005E, 0x0F40, 0x0067, 0x1CC0, 0x006B, 0x1AC0, 0x006D, 0x16C0, 0x006E, 0x0EC0, 0x0073, 0x19C0, 0x0075, 0x15C0, 0x0076, 0x0DC0, 0x0079, 0x13C0, 0x007A, 0x0BC0, 0x007C, 0x07C0,
0x008F, 0x1E20, 0x0097, 0x1D20, 0x009B, 0x1B20, 0x009D, 0x1720, 0x009E, 0x0F20, 0x00A7, 0x1CA0, 0x00AB, 0x1AA0, 0x00AD, 0x16A0, 0x00AE, 0x0EA0, 0x00B3, 0x19A0, 0x00B5, 0x15A0, 0x00B6,
0x0DA0, 0x00B9, 0x13A0, 0x00BA, 0x0BA0, 0x00BC, 0x07A0, 0x00C7, 0x1C60, 0x00CB, 0x1A60, 0x00CD, 0x1660, 0x00CE, 0x0E60, 0x00D3, 0x1960, 0x00D5, 0x1560, 0x00D6, 0x0D60, 0x00D9, 0x1360,
0x00DA, 0x0B60, 0x00DC, 0x0760, 0x00E3, 0x18E0, 0x00E5, 0x14E0, 0x00E6, 0x0CE0, 0x00E9, 0x12E0, 0x00EA, 0x0AE0, 0x00EC, 0x06E0, 0x00F1, 0x11E0, 0x00F2, 0x09E0, 0x00F4, 0x05E0, 0x00F8,
0x03E0, 0x010F, 0x1E10, 0x0117, 0x1D10, 0x011B, 0x1B10, 0x011D, 0x1710, 0x011E, 0x0F10, 0x0127, 0x1C90, 0x012B, 0x1A90, 0x012D, 0x1690, 0x012E, 0x0E90, 0x0133, 0x1990, 0x0135, 0x1590,
0x0136, 0x0D90, 0x0139, 0x1390, 0x013A, 0x0B90, 0x013C, 0x0790, 0x0147, 0x1C50, 0x014B, 0x1A50, 0x014D, 0x1650, 0x014E, 0x0E50, 0x0153, 0x1950, 0x0155, 0x1550, 0x0156, 0x0D50, 0x0159,
0x1350, 0x015A, 0x0B50, 0x015C, 0x0750, 0x0163, 0x18D0, 0x0165, 0x14D0, 0x0166, 0x0CD0, 0x0169, 0x12D0, 0x016A, 0x0AD0, 0x016C, 0x06D0, 0x0171, 0x11D0, 0x0172, 0x09D0, 0x0174, 0x05D0,
0x0178, 0x03D0, 0x0187, 0x1C30, 0x018B, 0x1A30, 0x018D, 0x1630, 0x018E, 0x0E30, 0x0193, 0x1930, 0x0195, 0x1530, 0x0196, 0x0D30, 0x0199, 0x1330, 0x019A, 0x0B30, 0x019C, 0x0730, 0x01A3,
0x18B0, 0x01A5, 0x14B0, 0x01A6, 0x0CB0, 0x01A9, 0x12B0, 0x01AA, 0x0AB0, 0x01AC, 0x06B0, 0x01B1, 0x11B0, 0x01B2, 0x09B0, 0x01B4, 0x05B0, 0x01B8, 0x03B0, 0x01C3, 0x1870, 0x01C5, 0x1470,
0x01C6, 0x0C70, 0x01C9, 0x1270, 0x01CA, 0x0A70, 0x01CC, 0x0670, 0x01D1, 0x1170, 0x01D2, 0x0970, 0x01D4, 0x0570, 0x01D8, 0x0370, 0x01E1, 0x10F0, 0x01E2, 0x08F0, 0x01E4, 0x04F0, 0x01E8,
0x02F0, 0x020F, 0x1E08, 0x0217, 0x1D08, 0x021B, 0x1B08, 0x021D, 0x1708, 0x021E, 0x0F08, 0x0227, 0x1C88, 0x022B, 0x1A88, 0x022D, 0x1688, 0x022E, 0x0E88, 0x0233, 0x1988, 0x0235, 0x1588,
0x0236, 0x0D88, 0x0239, 0x1388, 0x023A, 0x0B88, 0x023C, 0x0788, 0x0247, 0x1C48, 0x024B, 0x1A48, 0x024D, 0x1648, 0x024E, 0x0E48, 0x0253, 0x1948, 0x0255, 0x1548, 0x0256, 0x0D48, 0x0259,
0x1348, 0x025A, 0x0B48, 0x025C, 0x0748, 0x0263, 0x18C8, 0x0265, 0x14C8, 0x0266, 0x0CC8, 0x0269, 0x12C8, 0x026A, 0x0AC8, 0x026C, 0x06C8, 0x0271, 0x11C8, 0x0272, 0x09C8, 0x0274, 0x05C8,
0x0278, 0x03C8, 0x0287, 0x1C28, 0x028B, 0x1A28, 0x028D, 0x1628, 0x028E, 0x0E28, 0x0293, 0x1928, 0x0295, 0x1528, 0x0296, 0x0D28, 0x0299, 0x1328, 0x029A, 0x0B28, 0x029C, 0x0728, 0x02A3,
0x18A8, 0x02A5, 0x14A8, 0x02A6, 0x0CA8, 0x02A9, 0x12A8, 0x02AA, 0x0AA8, 0x02AC, 0x06A8, 0x02B1, 0x11A8, 0x02B2, 0x09A8, 0x02B4, 0x05A8, 0x02B8, 0x03A8, 0x02C3, 0x1868, 0x02C5, 0x1468,
0x02C6, 0x0C68, 0x02C9, 0x1268, 0x02CA, 0x0A68, 0x02CC, 0x0668, 0x02D1, 0x1168, 0x02D2, 0x0968, 0x02D4, 0x0568, 0x02D8, 0x0368, 0x02E1, 0x10E8, 0x02E2, 0x08E8, 0x02E4, 0x04E8, 0x0307,
0x1C18, 0x030B, 0x1A18, 0x030D, 0x1618, 0x030E, 0x0E18, 0x0313, 0x1918, 0x0315, 0x1518, 0x0316, 0x0D18, 0x0319, 0x1318, 0x031A, 0x0B18, 0x031C, 0x0718, 0x0323, 0x1898, 0x0325, 0x1498,
0x0326, 0x0C98, 0x0329, 0x1298, 0x032A, 0x0A98, 0x032C, 0x0698, 0x0331, 0x1198, 0x0332, 0x0998, 0x0334, 0x0598, 0x0338, 0x0398, 0x0343, 0x1858, 0x0345, 0x1458, 0x0346, 0x0C58, 0x0349,
0x1258, 0x034A, 0x0A58, 0x034C, 0x0658, 0x0351, 0x1158, 0x0352, 0x0958, 0x0354, 0x0558, 0x0361, 0x10D8, 0x0362, 0x08D8, 0x0364, 0x04D8, 0x0383, 0x1838, 0x0385, 0x1438, 0x0386, 0x0C38,
0x0389, 0x1238, 0x038A, 0x0A38, 0x038C, 0x0638, 0x0391, 0x1138, 0x0392, 0x0938, 0x0394, 0x0538, 0x03A1, 0x10B8, 0x03A2, 0x08B8, 0x03A4, 0x04B8, 0x03C1, 0x1078, 0x03C2, 0x0878, 0x03C4,
0x0478, 0x040F, 0x1E04, 0x0417, 0x1D04, 0x041B, 0x1B04, 0x041D, 0x1704, 0x041E, 0x0F04, 0x0427, 0x1C84, 0x042B, 0x1A84, 0x042D, 0x1684, 0x042E, 0x0E84, 0x0433, 0x1984, 0x0435, 0x1584,
0x0436, 0x0D84, 0x0439, 0x1384, 0x043A, 0x0B84, 0x043C, 0x0784, 0x0447, 0x1C44, 0x044B, 0x1A44, 0x044D, 0x1644, 0x044E, 0x0E44, 0x0453, 0x1944, 0x0455, 0x1544, 0x0456, 0x0D44, 0x0459,
0x1344, 0x045A, 0x0B44, 0x045C, 0x0744, 0x0463, 0x18C4, 0x0465, 0x14C4, 0x0466, 0x0CC4, 0x0469, 0x12C4, 0x046A, 0x0AC4, 0x046C, 0x06C4, 0x0471, 0x11C4, 0x0472, 0x09C4, 0x0474, 0x05C4,
0x0487, 0x1C24, 0x048B, 0x1A24, 0x048D, 0x1624, 0x048E, 0x0E24, 0x0493, 0x1924, 0x0495, 0x1524, 0x0496, 0x0D24, 0x0499, 0x1324, 0x049A, 0x0B24, 0x049C, 0x0724, 0x04A3, 0x18A4, 0x04A5,
0x14A4, 0x04A6, 0x0CA4, 0x04A9, 0x12A4, 0x04AA, 0x0AA4, 0x04AC, 0x06A4, 0x04B1, 0x11A4, 0x04B2, 0x09A4, 0x04B4, 0x05A4, 0x04C3, 0x1864, 0x04C5, 0x1464, 0x04C6, 0x0C64, 0x04C9, 0x1264,
0x04CA, 0x0A64, 0x04CC, 0x0664, 0x04D1, 0x1164, 0x04D2, 0x0964, 0x04D4, 0x0564, 0x04E1, 0x10E4, 0x04E2, 0x08E4, 0x0507, 0x1C14, 0x050B, 0x1A14, 0x050D, 0x1614, 0x050E, 0x0E14, 0x0513,
0x1914, 0x0515, 0x1514, 0x0516, 0x0D14, 0x0519, 0x1314, 0x051A, 0x0B14, 0x051C, 0x0714, 0x0523, 0x1894, 0x0525, 0x1494, 0x0526, 0x0C94, 0x0529, 0x1294, 0x052A, 0x0A94, 0x052C, 0x0694,
0x0531, 0x1194, 0x0532, 0x0994, 0x0534, 0x0594, 0x0543, 0x1854, 0x0545, 0x1454, 0x0546, 0x0C54, 0x0549, 0x1254, 0x054A, 0x0A54, 0x054C, 0x0654, 0x0551, 0x1154, 0x0552, 0x0954, 0x0561,
0x10D4, 0x0562, 0x08D4, 0x0583, 0x1834, 0x0585, 0x1434, 0x0586, 0x0C34, 0x0589, 0x1234, 0x058A, 0x0A34, 0x058C, 0x0634, 0x0591, 0x1134, 0x0592, 0x0934, 0x05A1, 0x10B4, 0x05A2, 0x08B4,
0x05C1, 0x1074, 0x05C2, 0x0874, 0x0607, 0x1C0C, 0x060B, 0x1A0C, 0x060D, 0x160C, 0x060E, 0x0E0C, 0x0613, 0x190C, 0x0615, 0x150C, 0x0616, 0x0D0C, 0x0619, 0x130C, 0x061A, 0x0B0C, 0x061C,
0x070C, 0x0623, 0x188C, 0x0625, 0x148C, 0x0626, 0x0C8C, 0x0629, 0x128C, 0x062A, 0x0A8C, 0x062C, 0x068C, 0x0631, 0x118C, 0x0632, 0x098C, 0x0643, 0x184C, 0x0645, 0x144C, 0x0646, 0x0C4C,
0x0649, 0x124C, 0x064A, 0x0A4C, 0x0651, 0x114C, 0x0652, 0x094C, 0x0661, 0x10CC, 0x0662, 0x08CC, 0x0683, 0x182C, 0x0685, 0x142C, 0x0686, 0x0C2C, 0x0689, 0x122C, 0x068A, 0x0A2C, 0x0691,
0x112C, 0x0692, 0x092C, 0x06A1, 0x10AC, 0x06A2, 0x08AC, 0x06C1, 0x106C, 0x06C2, 0x086C, 0x0703, 0x181C, 0x0705, 0x141C, 0x0706, 0x0C1C, 0x0709, 0x121C, 0x070A, 0x0A1C, 0x0711, 0x111C,
0x0712, 0x091C, 0x0721, 0x109C, 0x0722, 0x089C, 0x0741, 0x105C, 0x0742, 0x085C, 0x0781, 0x103C, 0x0782, 0x083C, 0x080F, 0x1E02, 0x0817, 0x1D02, 0x081B, 0x1B02, 0x081D, 0x1702, 0x081E,
0x0F02, 0x0827, 0x1C82, 0x082B, 0x1A82, 0x082D, 0x1682, 0x082E, 0x0E82, 0x0833, 0x1982, 0x0835, 0x1582, 0x0836, 0x0D82, 0x0839, 0x1382, 0x083A, 0x0B82, 0x0847, 0x1C42, 0x084B, 0x1A42,
0x084D, 0x1642, 0x084E, 0x0E42, 0x0853, 0x1942, 0x0855, 0x1542, 0x0856, 0x0D42, 0x0859, 0x1342, 0x085A, 0x0B42, 0x0863, 0x18C2, 0x0865, 0x14C2, 0x0866, 0x0CC2, 0x0869, 0x12C2, 0x086A,
0x0AC2, 0x0871, 0x11C2, 0x0872, 0x09C2, 0x0887, 0x1C22, 0x088B, 0x1A22, 0x088D, 0x1622, 0x088E, 0x0E22, 0x0893, 0x1922, 0x0895, 0x1522, 0x0896, 0x0D22, 0x0899, 0x1322, 0x089A, 0x0B22,
0x08A3, 0x18A2, 0x08A5, 0x14A2, 0x08A6, 0x0CA2, 0x08A9, 0x12A2, 0x08AA, 0x0AA2, 0x08B1, 0x11A2, 0x08B2, 0x09A2, 0x08C3, 0x1862, 0x08C5, 0x1462, 0x08C6, 0x0C62, 0x08C9, 0x1262, 0x08CA,
0x0A62, 0x08D1, 0x1162, 0x08D2, 0x0962, 0x08E1, 0x10E2, 0x0907, 0x1C12, 0x090B, 0x1A12, 0x090D, 0x1612, 0x090E, 0x0E12, 0x0913, 0x1912, 0x0915, 0x1512, 0x0916, 0x0D12, 0x0919, 0x1312,
0x091A, 0x0B12, 0x0923, 0x1892, 0x0925, 0x1492, 0x0926, 0x0C92, 0x0929, 0x1292, 0x092A, 0x0A92, 0x0931, 0x1192, 0x0932, 0x0992, 0x0943, 0x1852, 0x0945, 0x1452, 0x0946, 0x0C52, 0x0949,
0x1252, 0x094A, 0x0A52, 0x0951, 0x1152, 0x0961, 0x10D2, 0x0983, 0x1832, 0x0985, 0x1432, 0x0986, 0x0C32, 0x0989, 0x1232, 0x098A, 0x0A32, 0x0991, 0x1132, 0x09A1, 0x10B2, 0x09C1, 0x1072,
0x0A07, 0x1C0A, 0x0A0B, 0x1A0A, 0x0A0D, 0x160A, 0x0A0E, 0x0E0A, 0x0A13, 0x190A, 0x0A15, 0x150A, 0x0A16, 0x0D0A, 0x0A19, 0x130A, 0x0A1A, 0x0B0A, 0x0A23, 0x188A, 0x0A25, 0x148A, 0x0A26,
0x0C8A, 0x0A29, 0x128A, 0x0A2A, 0x0A8A, 0x0A31, 0x118A, 0x0A43, 0x184A, 0x0A45, 0x144A, 0x0A46, 0x0C4A, 0x0A49, 0x124A, 0x0A51, 0x114A, 0x0A61, 0x10CA, 0x0A83, 0x182A, 0x0A85, 0x142A,
0x0A86, 0x0C2A, 0x0A89, 0x122A, 0x0A91, 0x112A, 0x0AA1, 0x10AA, 0x0AC1, 0x106A, 0x0B03, 0x181A, 0x0B05, 0x141A, 0x0B06, 0x0C1A, 0x0B09, 0x121A, 0x0B11, 0x111A, 0x0B21, 0x109A, 0x0B41,
0x105A, 0x0B81, 0x103A, 0x0C07, 0x1C06, 0x0C0B, 0x1A06, 0x0C0D, 0x1606, 0x0C0E, 0x0E06, 0x0C13, 0x1906, 0x0C15, 0x1506, 0x0C16, 0x0D06, 0x0C19, 0x1306, 0x0C23, 0x1886, 0x0C25, 0x1486,
0x0C26, 0x0C86, 0x0C29, 0x1286, 0x0C31, 0x1186, 0x0C43, 0x1846, 0x0C45, 0x1446, 0x0C49, 0x1246, 0x0C51, 0x1146, 0x0C61, 0x10C6, 0x0C83, 0x1826, 0x0C85, 0x1426, 0x0C89, 0x1226, 0x0C91,
0x1126, 0x0CA1, 0x10A6, 0x0CC1, 0x1066, 0x0D03, 0x1816, 0x0D05, 0x1416, 0x0D09, 0x1216, 0x0D11, 0x1116, 0x0D21, 0x1096, 0x0D41, 0x1056, 0x0D81, 0x1036, 0x0E03, 0x180E, 0x0E05, 0x140E,
0x0E09, 0x120E, 0x0E11, 0x110E, 0x0E21, 0x108E, 0x0E41, 0x104E, 0x0E81, 0x102E, 0x0F01, 0x101E, 0x100F, 0x1E01, 0x1017, 0x1D01, 0x101B, 0x1B01, 0x101D, 0x1701, 0x1027, 0x1C81, 0x102B,
0x1A81, 0x102D, 0x1681, 0x1033, 0x1981, 0x1035, 0x1581, 0x1039, 0x1381, 0x1047, 0x1C41, 0x104B, 0x1A41, 0x104D, 0x1641, 0x1053, 0x1941, 0x1055, 0x1541, 0x1059, 0x1341, 0x1063, 0x18C1,
0x1065, 0x14C1, 0x1069, 0x12C1, 0x1071, 0x11C1, 0x1087, 0x1C21, 0x108B, 0x1A21, 0x108D, 0x1621, 0x1093, 0x1921, 0x1095, 0x1521, 0x1099, 0x1321, 0x10A3, 0x18A1, 0x10A5, 0x14A1, 0x10A9,
0x12A1, 0x10B1, 0x11A1, 0x10C3, 0x1861, 0x10C5, 0x1461, 0x10C9, 0x1261, 0x10D1, 0x1161, 0x1107, 0x1C11, 0x110B, 0x1A11, 0x110D, 0x1611, 0x1113, 0x1911, 0x1115, 0x1511, 0x1119, 0x1311,
0x1123, 0x1891, 0x1125, 0x1491, 0x1129, 0x1291, 0x1131, 0x1191, 0x1143, 0x1851, 0x1145, 0x1451, 0x1149, 0x1251, 0x1183, 0x1831, 0x1185, 0x1431, 0x1189, 0x1231, 0x1207, 0x1C09, 0x120B,
0x1A09, 0x120D, 0x1609, 0x1213, 0x1909, 0x1215, 0x1509, 0x1219, 0x1309, 0x1223, 0x1889, 0x1225, 0x1489, 0x1229, 0x1289, 0x1243, 0x1849, 0x1245, 0x1449, 0x1283, 0x1829, 0x1285, 0x1429,
0x1303, 0x1819, 0x1305, 0x1419, 0x1407, 0x1C05, 0x140B, 0x1A05, 0x140D, 0x1605, 0x1413, 0x1905, 0x1415, 0x1505, 0x1423, 0x1885, 0x1425, 0x1485, 0x1443, 0x1845, 0x1483, 0x1825, 0x1503,
0x1815, 0x1603, 0x180D, 0x1807, 0x1C03, 0x180B, 0x1A03, 0x1813, 0x1903, 0x1823, 0x1883, 0x1843, 0x1445, 0x1249, 0x1151, 0x10E1, 0x0C46, 0x0A4A, 0x0952, 0x08E2, 0x064C, 0x0554, 0x04E4,
0x0358, 0x02E8, 0x01F0 };
 
/** Appendix D Table II - 2 of 13 characters */
private static final int[] APPX_D_II = { 0x0003, 0x1800, 0x0005, 0x1400, 0x0006, 0x0C00, 0x0009, 0x1200, 0x000A, 0x0A00, 0x000C, 0x0600, 0x0011, 0x1100, 0x0012, 0x0900, 0x0014, 0x0500, 0x0018,
0x0300, 0x0021, 0x1080, 0x0022, 0x0880, 0x0024, 0x0480, 0x0028, 0x0280, 0x0030, 0x0180, 0x0041, 0x1040, 0x0042, 0x0840, 0x0044, 0x0440, 0x0048, 0x0240, 0x0050, 0x0140, 0x0060, 0x00C0,
0x0081, 0x1020, 0x0082, 0x0820, 0x0084, 0x0420, 0x0088, 0x0220, 0x0090, 0x0120, 0x0101, 0x1010, 0x0102, 0x0810, 0x0104, 0x0410, 0x0108, 0x0210, 0x0201, 0x1008, 0x0202, 0x0808, 0x0204,
0x0408, 0x0401, 0x1004, 0x0402, 0x0804, 0x0801, 0x1002, 0x1001, 0x0802, 0x0404, 0x0208, 0x0110, 0x00A0 };
 
/** Appendix D Table IV - Bar-to-Character Mapping (reverse lookup) */
private static final int[] APPX_D_IV = { 67, 6, 78, 16, 86, 95, 34, 40, 45, 113, 117, 121, 62, 87, 18, 104, 41, 76, 57, 119, 115, 72, 97, 2, 127, 26, 105, 35, 122, 52, 114, 7, 24, 82, 68, 63, 94,
44, 77, 112, 70, 100, 39, 30, 107, 15, 125, 85, 10, 65, 54, 88, 20, 106, 46, 66, 8, 116, 29, 61, 99, 80, 90, 37, 123, 51, 25, 84, 129, 56, 4, 109, 96, 28, 36, 47, 11, 71, 33, 102, 21, 9,
17, 49, 124, 79, 64, 91, 42, 69, 53, 60, 14, 1, 27, 103, 126, 75, 89, 50, 120, 19, 32, 110, 92, 111, 130, 59, 31, 12, 81, 43, 55, 5, 74, 22, 101, 128, 58, 118, 48, 108, 38, 98, 93, 23, 83,
13, 73, 3 };
 
public UspsOneCode() {
this.default_height = 8;
this.humanReadableLocation = HumanReadableLocation.NONE;
this.humanReadableAlignment = HumanReadableAlignment.LEFT; // spec section 2.4.2
}
 
@Override
protected void encode() {
String zip = "";
String zip_adder;
String tracker = "";
int i, j;
final int length = this.content.length();
BigInteger accum;
BigInteger x_reg;
BigInteger mask;
int usps_crc;
final int[] codeword = new int[10];
final int[] characters = new int[10];
final boolean[] bar_map = new boolean[130];
char c;
 
if (!this.content.matches("[0-9\u002D]+")) {
throw new OkapiException("Invalid characters in input data");
}
 
if (length > 32) {
throw new OkapiException("Input too long");
}
 
/* separate the tracking code from the routing code */
j = 0;
for (i = 0; i < length; i++) {
if (this.content.charAt(i) == '-') {
j = 1;
} else {
if (j == 0) {
/* reading tracker */
tracker += this.content.charAt(i);
} else {
/* reading zip code */
zip += this.content.charAt(i);
}
}
}
 
if (tracker.length() != 20) {