1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package org.millscript.office.spreadsheet.formula.functions;
22
23 import org.millscript.commons.alert.Alert;
24 import org.millscript.millscript.alert.Alerts;
25 import org.millscript.millscript.datatypes.Deferred;
26 import org.millscript.millscript.functions.UnaryFunction;
27 import org.millscript.millscript.vm.Package;
28 import org.millscript.millscript.vm.Ref;
29 import org.millscript.office.spreadsheet.CellRef;
30 import org.millscript.office.spreadsheet.formula.CellAddress;
31
32 /**
33 *
34 */
35 public class RefFunction extends UnaryFunction {
36
37 /**
38 * Utility method for generating an Alert with a given message and the
39 * specified object as a culprit.
40 *
41 * @param msg the alert message
42 * @param obj the culprit object
43 * @return a new Alert for the specified message and object
44 */
45 private static Alert oops( final String msg, final Object obj ) {
46 return Alerts.eval( msg, null ).culprit( "object", obj ).mishap();
47 }
48
49 /**
50 * Casts the supplied Object to a CellAddress.
51 *
52 * @param x an object to cast to a CellAddress
53 * @return a CellAddress cast from the specified object
54 */
55 public static CellAddress toCellAddress( final Object x ) {
56 try {
57 if ( x != null ) {
58 return (CellAddress)x;
59 }
60 throw oops( "Boolean needed", x );
61 } catch ( ClassCastException ex ) {
62 try {
63 return toCellAddress( ((Deferred< ? >) x).get() );
64 } catch ( ClassCastException ex2 ) {
65 throw oops( "Boolean needed", x );
66 }
67 }
68 }
69
70 /**
71 * The Ref for the global current cell variable.
72 */
73 private final Ref cellRef;
74
75 /**
76 * @see UnaryFunction#UnaryFunction(Package)
77 */
78 public RefFunction( final Package p ) {
79 super( p );
80 this.cellRef = p.findIdentFor( null, "cell" ).getRef();
81 }
82
83 /**
84 * @see org.millscript.millscript.functions.UnaryFunction#apply1(java.lang.Object)
85 */
86 @Override
87 public Object apply1( final Object a1 ) {
88 final CellRef currentCell = (CellRef) this.cellRef.value;
89 final CellAddress cellAddress = toCellAddress( a1 );
90 final CellRef addressedCell = currentCell.getRowRef().getWorksheetRef().get(
91 cellAddress.getRowRelativeTo( currentCell )
92 ).get(
93 cellAddress.getColumnRelativeTo( currentCell )
94 );
95 return addressedCell;
96 }
97
98 }