repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
soot
soot-master/tutorial/guide/examples/intermediate_representation/src/dk/brics/soot/intermediate/translation/StmtTranslator.java
package dk.brics.soot.intermediate.translation; import java.util.HashMap; import java.util.Map; import soot.Local; import soot.SootClass; import soot.SootMethod; import soot.Value; import soot.jimple.AbstractStmtSwitch; import soot.jimple.ArrayRef; import soot.jimple.AssignStmt; import soot.jimple.DefinitionStmt; import soot.jimple.FieldRef; import soot.jimple.IdentityStmt; import soot.jimple.InvokeExpr; import soot.jimple.InvokeStmt; import soot.jimple.ReturnStmt; import soot.jimple.ReturnVoidStmt; import soot.jimple.Stmt; import dk.brics.soot.intermediate.representation.Method; import dk.brics.soot.intermediate.representation.Nop; import dk.brics.soot.intermediate.representation.Return; import dk.brics.soot.intermediate.representation.Statement; import dk.brics.soot.intermediate.representation.Variable; import dk.brics.soot.intermediate.representation.Variable.Type; public class StmtTranslator extends AbstractStmtSwitch { JavaTranslator jt; private SootClass currentClass; private SootMethod currentMethod; private Map<Stmt, Statement> firstStmtToStatement; private Map<Stmt, Statement> lastStmtToStatement; Map<Local,Variable> local_var = new HashMap<Local,Variable>(); private Statement first_statement; private Statement last_statement; private ExprTranslator et; public StmtTranslator(JavaTranslator translator) { jt = translator; firstStmtToStatement = new HashMap<Stmt, Statement>(); lastStmtToStatement = new HashMap<Stmt, Statement>(); et = new ExprTranslator(jt, this); } public void setCurrentClass(SootClass sc) { this.currentClass = sc; } public void setCurrentMethod(SootMethod sm) { this.currentMethod = sm; } public void translateStmt(Stmt stmt) { first_statement = null; last_statement = null; stmt.apply(this); if (first_statement == null) { addStatement(new Nop()); } firstStmtToStatement.put(stmt, first_statement); lastStmtToStatement.put(stmt, last_statement); } void addStatement(Statement s) { ((Method)jt.methodsignaturToMethod.get(currentMethod.getSignature())).addStatement(s); if (first_statement == null) { first_statement = s; } else { last_statement.addSucc(s); } last_statement = s; } public Statement getFirst(Stmt stmt) { return firstStmtToStatement.get(stmt); } public Statement getLast(Stmt stmt) { return lastStmtToStatement.get(stmt); } Variable getLocalVariable(Local l) { if (local_var.containsKey(l)) { return (Variable)local_var.get(l); } Variable var = jt.makeVariable(l); local_var.put(l, var); return var; } public void caseInvokeStmt(InvokeStmt stmt) { InvokeExpr expr = stmt.getInvokeExpr(); Variable lvar = jt.makeVariable(expr); et.translateExpr(lvar, stmt.getInvokeExprBox()); } public void caseAssignStmt(AssignStmt stmt) { handleAssign(stmt); } public void caseIdentityStmt(IdentityStmt stmt) { handleAssign(stmt); } public void caseReturnStmt(ReturnStmt stmt) { Variable rvar = jt.makeVariable(stmt.getOp()); Return r = new Return(); r.setAssignmentTarget(rvar); addStatement(r); } public void caseReturnVoidStmt(ReturnVoidStmt stmt) { Return r = new Return(); r.setAssignmentTarget(null); addStatement(r); } public void defaultCase(Stmt stmt) { addStatement(new Nop()); } void handleAssign(DefinitionStmt stmt) { Value lval = stmt.getLeftOp(); Value rval = stmt.getRightOp(); Variable rvar; if (lval instanceof Local) { rvar = getLocalVariable((Local)lval); } else { rvar = jt.makeVariable(rval); } et.translateExpr(rvar, stmt.getRightOpBox()); if (lval instanceof ArrayRef) { notSupported("We do not support arrays"); } else if (lval instanceof FieldRef) { notSupported("We do not support field references"); } } private void notSupported(String msg) { System.err.println(msg); System.exit(5); } }
3,881
25.053691
88
java
soot
soot-master/tutorial/guide/examples/pointsto/src/dk/brics/paddle/PointsToAnalysis.java
package dk.brics.paddle; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import soot.EntryPoints; import soot.Local; import soot.PointsToSet; import soot.Scene; import soot.SootClass; import soot.SootField; import soot.SootMethod; import soot.Value; import soot.ValueBox; import soot.jimple.JimpleBody; import soot.jimple.Stmt; import soot.jimple.paddle.PaddleTransformer; import soot.jimple.spark.SparkTransformer; import soot.options.PaddleOptions; import soot.tagkit.LineNumberTag; public class PointsToAnalysis { // Make sure we get line numbers and whole program analysis static { soot.options.Options.v().set_keep_line_number(true); soot.options.Options.v().set_whole_program(true); soot.options.Options.v().setPhaseOption("cg","verbose:true"); } private static SootClass loadClass(String name, boolean main) { SootClass c = Scene.v().loadClassAndSupport(name); c.setApplicationClass(); if (main) Scene.v().setMainClass(c); return c; } public static void main(String[] args) { loadClass("Item",false); loadClass("Container",false); SootClass c = loadClass(args[1],true); soot.Scene.v().loadNecessaryClasses(); soot.Scene.v().setEntryPoints(EntryPoints.v().all()); if (args[0].equals("paddle")) setPaddlePointsToAnalysis(); else if (args[0].equals("spark")) setSparkPointsToAnalysis(); SootField f = getField("Container","item"); Map/*<Local>*/ ls = getLocals(c,args[2],"Container"); printLocalIntersects(ls); printFieldIntersects(ls,f); } static void setSparkPointsToAnalysis() { System.out.println("[spark] Starting analysis ..."); HashMap opt = new HashMap(); opt.put("enabled","true"); opt.put("verbose","true"); opt.put("ignore-types","false"); opt.put("force-gc","false"); opt.put("pre-jimplify","false"); opt.put("vta","false"); opt.put("rta","false"); opt.put("field-based","false"); opt.put("types-for-sites","false"); opt.put("merge-stringbuffer","true"); opt.put("string-constants","false"); opt.put("simulate-natives","true"); opt.put("simple-edges-bidirectional","false"); opt.put("on-fly-cg","true"); opt.put("simplify-offline","false"); opt.put("simplify-sccs","false"); opt.put("ignore-types-for-sccs","false"); opt.put("propagator","worklist"); opt.put("set-impl","double"); opt.put("double-set-old","hybrid"); opt.put("double-set-new","hybrid"); opt.put("dump-html","false"); opt.put("dump-pag","false"); opt.put("dump-solution","false"); opt.put("topo-sort","false"); opt.put("dump-types","true"); opt.put("class-method-var","true"); opt.put("dump-answer","false"); opt.put("add-tags","false"); opt.put("set-mass","false"); SparkTransformer.v().transform("",opt); System.out.println("[spark] Done!"); } private static void setPaddlePointsToAnalysis() { System.out.println("[paddle] Starting analysis ..."); System.err.println("Soot version string: "+soot.Main.v().versionString); HashMap opt = new HashMap(); opt.put("enabled","true"); opt.put("verbose","true"); opt.put("bdd","true"); opt.put("backend","buddy"); opt.put("context","kcfa"); opt.put("k","2"); // opt.put("context-heap","true"); opt.put("propagator","auto"); opt.put("conf","ofcg"); opt.put("order","32"); opt.put("q","auto"); opt.put("set-impl","double"); opt.put("double-set-old","hybrid"); opt.put("double-set-new","hybrid"); opt.put("pre-jimplify","false"); PaddleTransformer pt = new PaddleTransformer(); PaddleOptions paddle_opt = new PaddleOptions(opt); pt.setup(paddle_opt); pt.solve(paddle_opt); soot.jimple.paddle.Results.v().makeStandardSootResults(); System.out.println("[paddle] Done!"); } private static int getLineNumber(Stmt s) { Iterator ti = s.getTags().iterator(); while (ti.hasNext()) { Object o = ti.next(); if (o instanceof LineNumberTag) return Integer.parseInt(o.toString()); } return -1; } private static SootField getField(String classname, String fieldname) { Collection app = Scene.v().getApplicationClasses(); Iterator ci = app.iterator(); while (ci.hasNext()) { SootClass sc = (SootClass)ci.next(); if (sc.getName().equals(classname)) return sc.getFieldByName(fieldname); } throw new RuntimeException("Field "+fieldname+" was not found in class "+classname); } private static Map/*<Integer,Local>*/ getLocals(SootClass sc, String methodname, String typename) { Map res = new HashMap(); Iterator mi = sc.getMethods().iterator(); while (mi.hasNext()) { SootMethod sm = (SootMethod)mi.next(); System.err.println(sm.getName()); if (true && sm.getName().equals(methodname) && sm.isConcrete()) { JimpleBody jb = (JimpleBody)sm.retrieveActiveBody(); Iterator ui = jb.getUnits().iterator(); while (ui.hasNext()) { Stmt s = (Stmt)ui.next(); int line = getLineNumber(s); // find definitions Iterator bi = s.getDefBoxes().iterator(); while (bi.hasNext()) { Object o = bi.next(); if (o instanceof ValueBox) { Value v = ((ValueBox)o).getValue(); if (v.getType().toString().equals(typename) && v instanceof Local) res.put(new Integer(line),v); } } } } } return res; } private static void printLocalIntersects(Map/*<Integer,Local>*/ ls) { soot.PointsToAnalysis pta = Scene.v().getPointsToAnalysis(); Iterator i1 = ls.entrySet().iterator(); while (i1.hasNext()) { Map.Entry e1 = (Map.Entry)i1.next(); int p1 = ((Integer)e1.getKey()).intValue(); Local l1 = (Local)e1.getValue(); PointsToSet r1 = pta.reachingObjects(l1); Iterator i2 = ls.entrySet().iterator(); while (i2.hasNext()) { Map.Entry e2 = (Map.Entry)i2.next(); int p2 = ((Integer)e2.getKey()).intValue(); Local l2 = (Local)e2.getValue(); PointsToSet r2 = pta.reachingObjects(l2); if (p1<=p2) System.out.println("["+p1+","+p2+"]\t Container intersect? "+r1.hasNonEmptyIntersection(r2)); } } } private static void printFieldIntersects(Map/*<Integer,Local>*/ ls, SootField f) { soot.PointsToAnalysis pta = Scene.v().getPointsToAnalysis(); Iterator i1 = ls.entrySet().iterator(); while (i1.hasNext()) { Map.Entry e1 = (Map.Entry)i1.next(); int p1 = ((Integer)e1.getKey()).intValue(); Local l1 = (Local)e1.getValue(); PointsToSet r1 = pta.reachingObjects(l1,f); Iterator i2 = ls.entrySet().iterator(); while (i2.hasNext()) { Map.Entry e2 = (Map.Entry)i2.next(); int p2 = ((Integer)e2.getKey()).intValue(); Local l2 = (Local)e2.getValue(); PointsToSet r2 = pta.reachingObjects(l2,f); if (p1<=p2) System.out.println("["+p1+","+p2+"]\t Container.item intersect? "+r1.hasNonEmptyIntersection(r2)); } } } }
7,050
30.477679
103
java
soot
soot-master/tutorial/guide/examples/pointsto/test/Container.java
public class Container { private Item item;// = new Item(); void setItem(Item item) { this.item = item; } Item getItem() { return this.item; } }
159
12.333333
38
java
soot
soot-master/tutorial/guide/examples/pointsto/test/Item.java
public class Item { Object data; }
36
8.25
19
java
soot
soot-master/tutorial/guide/examples/pointsto/test/Test1.java
public class Test1 { public void go() { Container c1 = new Container(); Item i1 = new Item(); c1.setItem(i1); Container c2 = new Container(); Item i2 = new Item(); c2.setItem(i2); Container c3 = c2; } public static void main(String args[]) { new Test1().go(); } }
296
13.85
41
java
soot
soot-master/tutorial/guide/examples/pointsto/test/Test2.java
public class Test2 { public void go() { Container c1 = new Container(); Item i1 = new Item(); c1.setItem(i1); Container c2 = new Container(); Item i2 = new Item(); c2.setItem(i2); Container c3 = new Container(); Item i3; if ("1".equals(new Integer(1).toString())) i3 = i1; else i3 = i2; c3.setItem(i3); } public static void main(String[] args) { new Test2().go(); } }
414
14.961538
44
java
soot
soot-master/tutorial/guide/examples/representations/grimp/GrimpExample.java
public class GrimpExample { public static void main(String[] args) { GrimpExample f = new GrimpExample(); int a = 7; int b = 14; int x = (f.bar(21)+a)*b; } public int bar(int n) { return n+21; } }
221
17.5
42
java
soot
soot-master/tutorial/guide/examples/representations/jimple/JimpleExample.java
public class JimpleExample { public static void main(String[] args) { JimpleExample f = new JimpleExample(); f.foo(); } public void foo() { /* assume n%2 = 0 */ int n = 8; /*s*/int[] d = new /*s*/int[n]; /*s*/int[] result = new /*s*/int[n]; int i = 0; int j = 0; while (n>0) { /*s*/int[] dd = new /*s*/int[n/2]; while (i<n) { /*s*/int b = lt(d[i], d[i+1]); dd[j] = b*d[i] + (1-b)*d[i+1]; i = i+2; j = j+1; } System.out.println(dd); } System.out.println(result); } public int lt(int a, int b) { if (a>b) return 1; return 0; } }
662
17.416667
44
java
soot
soot-master/tutorial/guide/examples/representations/shimple/ShimpleExample.java
import java.util.*; public class ShimpleExample { public boolean as_long_as_it_takes = true; public int test() { int x = 100; while(as_long_as_it_takes) { if(x < 200) { x = 100; } else { x = 200; } } return x; } }
284
11.391304
44
java
soot
soot-master/tutorial/intro/Hello.java
public class Hello { public static void main(String[] args) { System.out.println("Hello world!"); } }
122
14.375
43
java
soot
soot-master/tutorial/optimizingCourse/examples/AvailableExpressions.java
/* * Created on Dec 30, 2004 */ /** * @author jlhotak */ public class AvailableExpressions { public static void main(String[] args) { int a = 0; int b = 0; int c = 0; int d = 0; int u = 0; int v = 0; int x = 0; int y = 0; u = a + b; v = c + d; while (x < 100){ x = b + c; y = c + d; } c = 3; } }
333
12.36
41
java
soot
soot-master/tutorial/optimizingCourse/examples/CommonSubExp.java
/* * Created on Dec 21, 2004 * */ /** * @author jlhotak */ public class CommonSubExp { public static void main(String[] args) { int x = 3; int y = 9; int b = 9; int c = 4; if (x < y){ x = b + c; } else { y = b + c; } int z = b + c; } }
280
8.689655
41
java
soot
soot-master/tutorial/optimizingCourse/examples/DominatorExample.java
public class DominatorExample { public static void main (String [] args){ int x = 9; for (int i = 9; i < 10; i++){ x++; } for (;;){ if (x < 4) break; x--; } do { x += 2; }while(x < 15); while (x > 10){ x -= 3; } while (true){ if (x > 47) break; x *= 3; } while (x > 4) { x--; if (x % 3 != 0) continue; System.out.println(x); } int [] arr = new int[9]; for (int m = 0; m < 10; m++){ x = 4; arr[4] = 8; arr[4] = m; arr[x] = 8; } } }
764
16.386364
45
java
soot
soot-master/tutorial/optimizingCourse/examples/GrimpExample.java
/* * Created on Dec 28, 2004 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ /** * @author jlhotak * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class GrimpExample { public static void main(String[] args) { int x = 0; int [] a = {1,2,3,4,5,6,7}; while (x < a[x++]){ x = x + a[4] + 2; } } }
486
19.291667
68
java
soot
soot-master/tutorial/optimizingCourse/examples/JimpleExample.java
/* * Created on Dec 28, 2004 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ /** * @author jlhotak * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class JimpleExample { public static void main(String[] args) { int x = 0; int [] a = {1,2,3,4,5,6,7}; while (x < a[x++]){ x = x + a[4] + 2; } } }
487
19.333333
68
java
soot
soot-master/tutorial/optimizingCourse/examples/LiveInteractive.java
/** * @author jlhotak * */ public class LiveInteractive { public void run (){ int x = 4; int z = x + 3; int i = 0; do { z = x * i; x = x - 1; i = i + 2; }while (i <20); int y = 9; z = y + 9; System.out.println(z); } }
257
10.217391
30
java
soot
soot-master/tutorial/optimizingCourse/examples/Liveness.java
/** * @author jlhotak * */ public class Liveness { public void run (){ int x = 4; int z = x + 3; for (int i = 0; i < 10; i++){ z = x * i; } int y = 9; z = y + 9; System.out.println(z); } }
214
10.944444
31
java
soot
soot-master/tutorial/optimizingCourse/examples/LoopInvariant.java
/* * Created on Dec 27, 2004 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ /** * @author jlhotak * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class LoopInvariant { public static void main(String[] args) { int x = 9; int z = 10; int y = 8; int k = 0; int m = 0; for (int i = 0; i < 100; i++){ y = x + z; System.out.println(y); k = x + i; int j = 9; m = j + 1; } } }
589
16.878788
68
java
soot
soot-master/tutorial/optimizingCourse/examples/ReachingDefs.java
public class ReachingDefs { public static void main (String [] args) { ReachingDefs rdt1 = new ReachingDefs(); rdt1.m(8); rdt1.n(); } public void m(int i){ int x = 4; int y = 3; if (i < 10) { x = 5; } else { x = 7; y = 18; } int j = x * y; } public void n(){ int x = 9; int y = 0; while (x < 10){ y = x + 3; x = x + 1; } int z = x + 2; } }
520
16.965517
47
java
soot
soot-master/tutorial/pldi03/examples/LiveVariablesAnalysis.java
package olhotak.liveness; import soot.*; import soot.util.*; import java.util.*; import soot.jimple.*; import soot.toolkits.graph.*; import soot.toolkits.scalar.*; class LiveVariablesAnalysis extends BackwardFlowAnalysis { protected void copy(Object src, Object dest) { FlowSet srcSet = (FlowSet) src; FlowSet destSet = (FlowSet) dest; srcSet.copy(destSet); } protected void merge(Object src1, Object src2, Object dest) { FlowSet srcSet1 = (FlowSet) src1; FlowSet srcSet2 = (FlowSet) src2; FlowSet destSet = (FlowSet) dest; srcSet1.union(srcSet2, destSet); } protected void flowThrough(Object srcValue, Object unit, Object destValue) { FlowSet dest = (FlowSet) destValue; FlowSet src = (FlowSet) srcValue; Unit s = (Unit) unit; src.copy (dest); // Take out kill set Iterator boxIt = s.getDefBoxes().iterator(); while (boxIt.hasNext()) { ValueBox box = (ValueBox) boxIt.next(); Value value = box.getValue(); if (value instanceof Local) dest.remove(value); } // Add gen set boxIt = s.getUseBoxes().iterator(); while (boxIt.hasNext()) { ValueBox box = (ValueBox) boxIt.next(); Value value = box.getValue(); if (value instanceof Local) dest.add(value); } } protected Object entryInitialFlow() { return new ArraySparseSet(); } protected Object newInitialFlow() { return new ArraySparseSet(); } LiveVariablesAnalysis(DirectedGraph g) { super(g); doAnalysis(); } }
1,773
23.30137
63
java
soot
soot-master/tutorial/pldi03/examples/Main.java
class Main { public static void main(String[] args) { soot.G.v().PackManager().getPack("tag").add(new soot.Transform("tag.null", new NullTagAggregator())); soot.Main.main(args); } }
191
26.428571
105
java
soot
soot-master/tutorial/pldi03/examples/NullExample.java
public class NullExample { int foo(Object o, String p) { if (o == null) { return 2; } int i = 2; i += p.length(); System.out.println(p); return 4; } }
231
14.466667
31
java
soot
soot-master/tutorial/pldi03/examples/NullTagAggregator.java
import soot.*; import java.util.*; import soot.baf.*; import soot.tagkit.*; import soot.jimple.toolkits.annotation.tags.NullCheckTag; /** The aggregator for NullCheckAttribute. */ public class NullTagAggregator extends ImportantTagAggregator { public NullTagAggregator() {} public boolean wantTag( Tag t ) { return (t instanceof NullCheckTag); } public String aggregatedName() { return "NullCheckAttribute"; } }
467
14.096774
61
java
soot
soot-master/tutorial/pldi03/examples/NullnessAnalysis.java
import soot.*; import soot.jimple.*; import soot.toolkits.scalar.*; import soot.toolkits.graph.*; import soot.util.*; import java.util.*; /** Tracks which locals are definitely non-null. * Author: Patrick Lam (plam@sable.mcgill.ca) * Based on BranchedRefVarsAnalysis by Janus Godard (janus@place.org). */ class NullnessAnalysis extends ForwardBranchedFlowAnalysis { protected void copy(Object src, Object dest) { FlowSet sourceSet = (FlowSet)src, destSet = (FlowSet) dest; sourceSet.copy(destSet); } protected void merge(Object src1, Object src2, Object dest) { FlowSet srcSet1 = (FlowSet) src1; FlowSet srcSet2 = (FlowSet) src2; FlowSet destSet = (FlowSet) dest; srcSet1.intersection(srcSet2, destSet); } FlowSet fullSet, emptySet; FlowUniverse allRefLocals; Map unitToGenerateSet; protected void flowThrough(Object srcValue, Unit unit, List fallOut, List branchOuts) { FlowSet dest; FlowSet src = (FlowSet) srcValue; Unit s = (Unit) unit; // Create working set. dest = (FlowSet)src.clone(); // Take out kill set. Iterator boxIt = s.getDefBoxes().iterator(); while (boxIt.hasNext()) { ValueBox box = (ValueBox) boxIt.next(); Value value = box.getValue(); if (value instanceof Local && value.getType() instanceof RefLikeType) dest.remove(value); } // Perform gen. dest.union((FlowSet)unitToGenerateSet.get(unit), dest); // Handle copy statements: // x = y && 'y' in src => add 'x' to dest if (s instanceof DefinitionStmt) { DefinitionStmt as = (DefinitionStmt) s; Value ro = as.getRightOp(); // extract cast argument if (ro instanceof CastExpr) ro = ((CastExpr) ro).getOp(); if (src.contains(ro) && as.getLeftOp() instanceof Local) dest.add(as.getLeftOp()); } // Copy the out value to the fallthrough box (don't need iterator) { Iterator it = fallOut.iterator(); while (it.hasNext()) { FlowSet fs = (FlowSet) (it.next()); copy(dest, fs); } } // Copy the out value to all branch boxes. { Iterator it = branchOuts.iterator(); while (it.hasNext()) { FlowSet fs = (FlowSet) (it.next()); copy(dest, fs); } } // Handle if statements by patching dest sets. if (unit instanceof IfStmt) { Value cond = ((IfStmt)unit).getCondition(); Value op1 = ((BinopExpr) cond).getOp1(); Value op2 = ((BinopExpr) cond).getOp2(); boolean isNeg = cond instanceof NeExpr; Value toGen = null; // case 1: opN is a local and opM is NullConstant // => opN nonnull on ne branch. if (op1 instanceof Local && op2 instanceof NullConstant) toGen = op1; if (op2 instanceof Local && op1 instanceof NullConstant) toGen = op2; if (toGen != null) { Iterator it = null; // if (toGen != null) goto l1: on branch, toGen nonnull. if (isNeg) it = branchOuts.iterator(); else it = fallOut.iterator(); while(it.hasNext()) { FlowSet fs = (FlowSet) (it.next()); fs.add(toGen); } } // case 2: both ops are local and one op is non-null and testing equality if (op1 instanceof Local && op2 instanceof Local && cond instanceof EqExpr) { toGen = null; if (src.contains(op1)) toGen = op2; if (src.contains(op2)) toGen = op1; if (toGen != null) { Iterator branchIt = branchOuts.iterator(); while (branchIt.hasNext()) { FlowSet fs = (FlowSet) (branchIt.next()); fs.add(toGen); } } } } } protected Object newInitialFlow() { return fullSet.clone(); } protected Object entryInitialFlow() { // everything could be null return emptySet.clone(); } private void addGen(Unit u, Value v) { ArraySparseSet l = (ArraySparseSet)unitToGenerateSet.get(u); l.add(v); } private void addGensFor(DefinitionStmt u) { Value lo = u.getLeftOp(); Value ro = u.getRightOp(); if (ro instanceof NewExpr || ro instanceof NewArrayExpr || ro instanceof NewMultiArrayExpr || ro instanceof ThisRef || ro instanceof CaughtExceptionRef) addGen(u, lo); } public NullnessAnalysis(UnitGraph g) { super(g); unitToGenerateSet = new HashMap(); Body b = g.getBody(); List refLocals = new LinkedList(); // set up universe, empty, full sets. emptySet = new ArraySparseSet(); fullSet = new ArraySparseSet(); // Find all locals in body. Iterator localIt = b.getLocals().iterator(); while (localIt.hasNext()) { Local l = (Local)localIt.next(); if (l.getType() instanceof RefLikeType) fullSet.add(l); } // Create gen sets. Iterator unitIt = b.getUnits().iterator(); while (unitIt.hasNext()) { Unit u = (Unit)unitIt.next(); unitToGenerateSet.put(u, new ArraySparseSet()); if (u instanceof DefinitionStmt) { Value lo = ((DefinitionStmt)u).getLeftOp(); if (lo instanceof Local && lo.getType() instanceof RefLikeType) addGensFor((DefinitionStmt)u); } Iterator boxIt = u.getUseAndDefBoxes().iterator(); while (boxIt.hasNext()) { Value boxValue = ((ValueBox) boxIt.next()).getValue(); Value base = null; if(boxValue instanceof InstanceFieldRef) { base = ((InstanceFieldRef) (boxValue)).getBase(); } else if (boxValue instanceof ArrayRef) { base = ((ArrayRef) (boxValue)).getBase(); } else if (boxValue instanceof InstanceInvokeExpr) { base = ((InstanceInvokeExpr) boxValue).getBase(); } else if (boxValue instanceof LengthExpr) { base = ((LengthExpr) boxValue).getOp(); } else if (u instanceof ThrowStmt) { base = ((ThrowStmt)u).getOp(); } else if (u instanceof MonitorStmt) { base = ((MonitorStmt)u).getOp(); } if (base != null && base instanceof Local && base.getType() instanceof RefLikeType) addGen(u, base); } } // Call superclass method to do work. doAnalysis(); } }
7,640
29.442231
85
java
soot
soot-master/tutorial/pldi03/examples/NullnessAnalysisColorer.java
/* Soot - a J*va Optimization Framework * Copyright (C) 2003 Jennifer Lhotak * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ import soot.*; import soot.tagkit.*; import soot.toolkits.graph.*; import java.util.*; import soot.toolkits.scalar.*; import soot.jimple.*; public class NullnessAnalysisColorer extends BodyTransformer { protected void internalTransform (Body b, String phaseName, Map options) { NullnessAnalysis analysis = new NullnessAnalysis (new CompleteUnitGraph(b)); Iterator it = b.getUnits().iterator(); while (it.hasNext()) { Stmt s = (Stmt)it.next(); Iterator usesIt = s.getUseBoxes().iterator(); FlowSet beforeSet = (FlowSet)analysis.getFlowBefore(s); while (usesIt.hasNext()) { ValueBox vBox = (ValueBox)usesIt.next(); addColorTags(vBox, beforeSet, s, analysis); } Iterator defsIt = s.getDefBoxes().iterator(); FlowSet afterSet = (FlowSet)analysis.getFallFlowAfter(s); while (defsIt.hasNext()){ ValueBox vBox = (ValueBox)defsIt.next(); addColorTags(vBox, afterSet, s, analysis); } } } private void addColorTags(ValueBox vBox, FlowSet set, Stmt s, NullnessAnalysis analysis) { Value val = vBox.getValue(); if (val.getType() instanceof RefLikeType && ((ArraySparseSet)set).contains(val)) vBox.addTag(new ColorTag(ColorTag.GREEN)); } }
2,300
35.52381
78
java
soot
soot-master/tutorial/pldi03/examples/NullnessDriver.java
import soot.Body; import soot.Main; import soot.Pack; import soot.PackManager; import soot.Transform; import soot.Unit; import soot.tagkit.StringTag; import soot.toolkits.scalar.ArraySparseSet; import soot.toolkits.graph.BriefUnitGraph; public class NullnessDriver { public static void main(String[] argv) { Pack jtp = soot.G.v().PackManager().getPack("jtp"); jtp.add(new Transform("jtp.nt", new NullTransformer())); jtp.add(new Transform("jtp.nac", new NullnessAnalysisColorer())); soot.Main.main(argv); } } class NullTransformer extends soot.BodyTransformer { protected void internalTransform(Body b, String phaseName, java.util.Map options) { NullnessAnalysis na = new NullnessAnalysis(new BriefUnitGraph(b)); java.util.Iterator uIt = b.getUnits().iterator(); while (uIt.hasNext()) { Unit u = (Unit)uIt.next(); StringBuffer n = new StringBuffer(); u.addTag(new StringTag("IN: "+na.getFlowBefore(u).toString())); if (u.fallsThrough()) { ArraySparseSet s = (ArraySparseSet)na.getFallFlowAfter(u); u.addTag(new StringTag("FALL: "+s.toString())); } if (u.branches()) { ArraySparseSet t = (ArraySparseSet)na. getBranchFlowAfter(u).get(0); u.addTag(new StringTag("BRANCH: "+t.toString())); } } } }
1,533
27.407407
75
java
soot
soot-master/tutorial/pldi03/examples/foo.java
class foo { public void sum(int[] a) { int total = 0; int i=0; int b = a[0]; for (i=0; i<a.length; i++) { total += a[i]; } int c = a[i]; } }
155
11
29
java
soot
soot-master/tutorial/profiler/Main.java
/* Soot - a J*va Optimization Framework * Copyright (C) 1997-1999 Raja Vallee-Rai * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /* * Modified by the Sable Research Group and others 1997-1999. * See the 'credits' file distributed with Soot for the complete list of * contributors. (Soot is distributed at http://www.sable.mcgill.ca/soot) */ /* Reference Version: $SootVersion: 1.beta.6.dev.51 $ */ package ashes.examples.countgotos; import soot.*; import soot.jimple.*; import soot.util.*; import java.io.*; import java.util.*; /** Example to instrument a classfile to produce goto counts. */ public class Main { public static void main(String[] args) { if(args.length == 0) { System.out.println("Syntax: java ashes.examples.countgotos.Main [soot options]"); System.exit(0); } PackManager.v().getPack("jtp").add(new Transform("jtp.instrumenter", GotoInstrumenter.v())); // Just in case, resolve the PrintStream and System SootClasses. Scene.v().addBasicClass("java.io.PrintStream",SootClass.SIGNATURES); Scene.v().addBasicClass("java.lang.System",SootClass.SIGNATURES); soot.Main.main(args); } } /** InstrumentClass example. Instruments the given class to print out the number of Jimple goto statements executed. To enable this class, enable the given PackAdjuster by compiling it separately, into the soot package. */ class GotoInstrumenter extends BodyTransformer { private static GotoInstrumenter instance = new GotoInstrumenter(); private GotoInstrumenter() {} public static GotoInstrumenter v() { return instance; } private boolean addedFieldToMainClassAndLoadedPrintStream = false; private SootClass javaIoPrintStream; private Local addTmpRef(Body body) { Local tmpRef = Jimple.v().newLocal("tmpRef", RefType.v("java.io.PrintStream")); body.getLocals().add(tmpRef); return tmpRef; } private Local addTmpLong(Body body) { Local tmpLong = Jimple.v().newLocal("tmpLong", LongType.v()); body.getLocals().add(tmpLong); return tmpLong; } private void addStmtsToBefore(Chain units, Stmt s, SootField gotoCounter, Local tmpRef, Local tmpLong) { // insert "tmpRef = java.lang.System.out;" units.insertBefore(Jimple.v().newAssignStmt( tmpRef, Jimple.v().newStaticFieldRef( Scene.v().getField("<java.lang.System: java.io.PrintStream out>").makeRef())), s); // insert "tmpLong = gotoCounter;" units.insertBefore(Jimple.v().newAssignStmt(tmpLong, Jimple.v().newStaticFieldRef(gotoCounter.makeRef())), s); // insert "tmpRef.println(tmpLong);" SootMethod toCall = javaIoPrintStream.getMethod("void println(long)"); units.insertBefore(Jimple.v().newInvokeStmt( Jimple.v().newVirtualInvokeExpr(tmpRef, toCall.makeRef(), tmpLong)), s); } protected void internalTransform(Body body, String phaseName, Map options) { SootClass sClass = body.getMethod().getDeclaringClass(); SootField gotoCounter = null; boolean addedLocals = false; Local tmpRef = null, tmpLong = null; Chain units = body.getUnits(); // Add code at the end of the main method to print out the // gotoCounter (this only works in simple cases, because you may have multiple returns or System.exit()'s ) synchronized(this) { if (!Scene.v().getMainClass(). declaresMethod("void main(java.lang.String[])")) throw new RuntimeException("couldn't find main() in mainClass"); if (addedFieldToMainClassAndLoadedPrintStream) gotoCounter = Scene.v().getMainClass().getFieldByName("gotoCount"); else { // Add gotoCounter field gotoCounter = new SootField("gotoCount", LongType.v(), Modifier.STATIC); Scene.v().getMainClass().addField(gotoCounter); javaIoPrintStream = Scene.v().getSootClass("java.io.PrintStream"); addedFieldToMainClassAndLoadedPrintStream = true; } } // Add code to increase goto counter each time a goto is encountered { boolean isMainMethod = body.getMethod().getSubSignature().equals("void main(java.lang.String[])"); Local tmpLocal = Jimple.v().newLocal("tmp", LongType.v()); body.getLocals().add(tmpLocal); Iterator stmtIt = units.snapshotIterator(); while(stmtIt.hasNext()) { Stmt s = (Stmt) stmtIt.next(); if(s instanceof GotoStmt) { AssignStmt toAdd1 = Jimple.v().newAssignStmt(tmpLocal, Jimple.v().newStaticFieldRef(gotoCounter.makeRef())); AssignStmt toAdd2 = Jimple.v().newAssignStmt(tmpLocal, Jimple.v().newAddExpr(tmpLocal, LongConstant.v(1L))); AssignStmt toAdd3 = Jimple.v().newAssignStmt(Jimple.v().newStaticFieldRef(gotoCounter.makeRef()), tmpLocal); // insert "tmpLocal = gotoCounter;" units.insertBefore(toAdd1, s); // insert "tmpLocal = tmpLocal + 1L;" units.insertBefore(toAdd2, s); // insert "gotoCounter = tmpLocal;" units.insertBefore(toAdd3, s); } else if (s instanceof InvokeStmt) { InvokeExpr iexpr = (InvokeExpr) ((InvokeStmt)s).getInvokeExpr(); if (iexpr instanceof StaticInvokeExpr) { SootMethod target = ((StaticInvokeExpr)iexpr).getMethod(); if (target.getSignature().equals("<java.lang.System: void exit(int)>")) { if (!addedLocals) { tmpRef = addTmpRef(body); tmpLong = addTmpLong(body); addedLocals = true; } addStmtsToBefore(units, s, gotoCounter, tmpRef, tmpLong); } } } else if (isMainMethod && (s instanceof ReturnStmt || s instanceof ReturnVoidStmt)) { if (!addedLocals) { tmpRef = addTmpRef(body); tmpLong = addTmpLong(body); addedLocals = true; } addStmtsToBefore(units, s, gotoCounter, tmpRef, tmpLong); } } } } }
7,884
38.034653
118
java
soot
soot-master/tutorial/profiler2/InvokeStaticInstrumenter.java
/* * InvokeStaticInstrumenter inserts count instructions before * INVOKESTATIC bytecode in a program. The instrumented program will * report how many static invocations happen in a run. * * Goal: * Insert counter instruction before static invocation instruction. * Report counters before program's normal exit point. * * Approach: * 1. Create a counter class which has a counter field, and * a reporting method. * 2. Take each method body, go through each instruction, and * insert count instructions before INVOKESTATIC. * 3. Make a call of reporting method of the counter class. * * Things to learn from this example: * 1. How to use Soot to examine a Java class. * 2. How to insert profiling instructions in a class. */ /* InvokeStaticInstrumenter extends the abstract class BodyTransformer, * and implements <pre>internalTransform</pre> method. */ import soot.*; import soot.jimple.*; import soot.util.*; import java.util.*; public class InvokeStaticInstrumenter extends BodyTransformer{ /* some internal fields */ static SootClass counterClass; static SootMethod increaseCounter, reportCounter; static { counterClass = Scene.v().loadClassAndSupport("MyCounter"); increaseCounter = counterClass.getMethod("void increase(int)"); reportCounter = counterClass.getMethod("void report()"); } /* internalTransform goes through a method body and inserts * counter instructions before an INVOKESTATIC instruction */ protected void internalTransform(Body body, String phase, Map options) { // body's method SootMethod method = body.getMethod(); // debugging System.out.println("instrumenting method : " + method.getSignature()); // get body's unit as a chain Chain units = body.getUnits(); // get a snapshot iterator of the unit since we are going to // mutate the chain when iterating over it. // Iterator stmtIt = units.snapshotIterator(); // typical while loop for iterating over each statement while (stmtIt.hasNext()) { // cast back to a statement. Stmt stmt = (Stmt)stmtIt.next(); // there are many kinds of statements, here we are only // interested in statements containing InvokeStatic // NOTE: there are two kinds of statements may contain // invoke expression: InvokeStmt, and AssignStmt if (!stmt.containsInvokeExpr()) { continue; } // take out the invoke expression InvokeExpr expr = (InvokeExpr)stmt.getInvokeExpr(); // now skip non-static invocations if (! (expr instanceof StaticInvokeExpr)) { continue; } // now we reach the real instruction // call Chain.insertBefore() to insert instructions // // 1. first, make a new invoke expression InvokeExpr incExpr= Jimple.v().newStaticInvokeExpr(increaseCounter.makeRef(), IntConstant.v(1)); // 2. then, make a invoke statement Stmt incStmt = Jimple.v().newInvokeStmt(incExpr); // 3. insert new statement into the chain // (we are mutating the unit chain). units.insertBefore(incStmt, stmt); } // Do not forget to insert instructions to report the counter // this only happens before the exit points of main method. // 1. check if this is the main method by checking signature String signature = method.getSubSignature(); boolean isMain = signature.equals("void main(java.lang.String[])"); // re-iterate the body to look for return statement if (isMain) { stmtIt = units.snapshotIterator(); while (stmtIt.hasNext()) { Stmt stmt = (Stmt)stmtIt.next(); // check if the instruction is a return with/without value if ((stmt instanceof ReturnStmt) ||(stmt instanceof ReturnVoidStmt)) { // 1. make invoke expression of MyCounter.report() InvokeExpr reportExpr= Jimple.v().newStaticInvokeExpr(reportCounter.makeRef()); // 2. then, make a invoke statement Stmt reportStmt = Jimple.v().newInvokeStmt(reportExpr); // 3. insert new statement into the chain // (we are mutating the unit chain). units.insertBefore(reportStmt, stmt); } } } } }
4,221
31.984375
83
java
soot
soot-master/tutorial/profiler2/MainDriver.java
/* Usage: java MainDriver appClass */ /* import necessary soot packages */ import soot.*; public class MainDriver { public static void main(String[] args) { /* check the arguments */ if (args.length == 0) { System.err.println("Usage: java MainDriver [options] classname"); System.exit(0); } /* add a phase to transformer pack by call Pack.add */ Pack jtp = PackManager.v().getPack("jtp"); jtp.add(new Transform("jtp.instrumenter", new InvokeStaticInstrumenter())); /* Give control to Soot to process all options, * InvokeStaticInstrumenter.internalTransform will get called. */ soot.Main.main(args); } }
681
22.517241
71
java
soot
soot-master/tutorial/profiler2/MyCounter.java
/* The counter class */ public class MyCounter { /* the counter, initialize to zero */ private static int c = 0; /** * increases the counter by <pre>howmany</pre> * @param howmany, the increment of the counter. */ public static synchronized void increase(int howmany) { c += howmany; } /** * reports the counter content. */ public static synchronized void report() { System.err.println("counter : " + c); } }
454
18.782609
57
java
soot
soot-master/tutorial/profiler2/TestInvoke.java
class TestInvoke { private static int calls=0; public static void main(String[] args) { for (int i=0; i<10; i++) { foo(); } System.out.println("I made "+calls+" static calls"); } private static void foo(){ calls++; bar(); } private static void bar(){ calls++; } }
295
13.095238
53
java
soot
soot-master/tutorial/tagclass/Main.java
/* Soot - a J*va Optimization Framework * Copyright (C) 1997-1999 Raja Vallee-Rai * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /* * Modified by the Sable Research Group and others 1997-1999. * See the 'credits' file distributed with Soot for the complete list of * contributors. (Soot is distributed at http://www.sable.mcgill.ca/soot) */ import soot.*; import soot.baf.*; import soot.jimple.*; import soot.options.Options; import soot.tagkit.*; import soot.util.*; import java.io.*; import java.util.*; /** Example of using Soot to create a classfile from scratch. * The 'createclass' example creates a HelloWorld class file using Soot. * It proceeds as follows: * * - Create a SootClass <code>HelloWorld</code> extending java.lang.Object. * * - Create a 'main' method and add it to the class. * * - Create an empty JimpleBody and add it to the 'main' method. * * - Add locals and statements to JimpleBody. * * - Write the result out to a class file. */ public class Main { public static void main(String[] args) throws FileNotFoundException, IOException { SootClass sClass; SootMethod method; // Resolve dependencies Scene.v().loadClassAndSupport("java.lang.Object"); Scene.v().loadClassAndSupport("java.lang.System"); // Declare 'public class HelloWorld' sClass = new SootClass("HelloWorld", Modifier.PUBLIC); // 'extends Object' sClass.setSuperclass(Scene.v().getSootClass("java.lang.Object")); Scene.v().addClass(sClass); // create and add the class attribute GenericAttribute classAttr = new GenericAttribute("MyClassAttr", "foo".getBytes()); sClass.addTag(classAttr); // Create the method, public static void main(String[]) method = new SootMethod("main", Arrays.asList(new Type[] {ArrayType.v(RefType.v("java.lang.String"), 1)}), VoidType.v(), Modifier.PUBLIC | Modifier.STATIC); sClass.addMethod(method); // Create and add the method attribute GenericAttribute mAttr = new GenericAttribute("MyMethodAttr", "".getBytes()); method.addTag(mAttr); // Create the method body { // create empty body JimpleBody body = Jimple.v().newBody(method); method.setActiveBody(body); Chain units = body.getUnits(); Local arg, tmpRef; Unit tmpUnit; // Add some locals, java.lang.String l0 arg = Jimple.v().newLocal("l0", ArrayType.v(RefType.v("java.lang.String"), 1)); body.getLocals().add(arg); // Add locals, java.io.printStream tmpRef tmpRef = Jimple.v().newLocal("tmpRef", RefType.v("java.io.PrintStream")); body.getLocals().add(tmpRef); // add "l0 = @parameter0" tmpUnit = Jimple.v().newIdentityStmt(arg, Jimple.v().newParameterRef(ArrayType.v(RefType.v("java.lang.String"), 1), 0)); tmpUnit.addTag(new MyTag(1)); units.add(tmpUnit); // add "tmpRef = java.lang.System.out" units.add(Jimple.v().newAssignStmt(tmpRef, Jimple.v().newStaticFieldRef( Scene.v().getField("<java.lang.System: java.io.PrintStream out>").makeRef()))); // insert "tmpRef.println("Hello world!")" { SootMethod toCall = Scene.v().getMethod("<java.io.PrintStream: void println(java.lang.String)>"); tmpUnit = Jimple.v().newInvokeStmt(Jimple.v().newVirtualInvokeExpr(tmpRef, toCall.makeRef(), StringConstant.v("Hello world!"))); tmpUnit.addTag(new MyTag(2)); units.add(tmpUnit); } // insert "return" units.add(Jimple.v().newReturnVoidStmt()); } MyTagAggregator mta = new MyTagAggregator(); // convert the body to Baf method.setActiveBody( Baf.v().newBody((JimpleBody) method.getActiveBody())); // aggregate the tags and produce a CodeAttribute mta.transform(method.getActiveBody()); // write the class to a file String fileName = SourceLocator.v().getFileNameFor(sClass, Options.output_format_class); OutputStream streamOut = new JasminOutputStream( new FileOutputStream(fileName)); PrintWriter writerOut = new PrintWriter( new OutputStreamWriter(streamOut)); AbstractJasminClass jasminClass = new soot.baf.JasminClass(sClass); jasminClass.print(writerOut); writerOut.flush(); streamOut.close(); } } class MyTag implements Tag { int value; public MyTag(int value) { this.value = value; } public String getName() { return "MyTag"; } // output the value as a 4-byte array public byte[] getValue() { ByteArrayOutputStream baos = new ByteArrayOutputStream(4); DataOutputStream dos = new DataOutputStream(baos); try { dos.writeInt(value); dos.flush(); } catch(IOException e) { System.err.println(e); throw new RuntimeException(e); } return baos.toByteArray(); } } class MyTagAggregator extends TagAggregator { public String aggregatedName() { return "MyTag"; } public boolean wantTag(Tag t) { return (t instanceof MyTag); } public void considerTag(Tag t, Unit u) { units.add(u); tags.add(t); } }
6,551
33.851064
144
java
null
jabref-main/buildSrc/src/main/java/module-info.java
open module org.jabref { requires javafx.base; }
53
12.5
25
java
null
jabref-main/buildSrc/src/main/java/org/jabref/logic/journals/Abbreviation.java
package org.jabref.logic.journals; import java.io.Serializable; import java.util.Objects; public class Abbreviation implements Comparable<Abbreviation>, Serializable { private static final long serialVersionUID = 1; private transient String name; private final String abbreviation; private transient String dotlessAbbreviation; // Is the empty string if not available private String shortestUniqueAbbreviation; public Abbreviation(String name, String abbreviation) { this(name, abbreviation, ""); } public Abbreviation(String name, String abbreviation, String shortestUniqueAbbreviation) { this(name, abbreviation, // "L. N." becomes "L N ", we need to remove the double spaces inbetween abbreviation.replace(".", " ").replace(" ", " ").trim(), shortestUniqueAbbreviation.trim()); } private Abbreviation(String name, String abbreviation, String dotlessAbbreviation, String shortestUniqueAbbreviation) { this.name = name.intern(); this.abbreviation = abbreviation.intern(); this.dotlessAbbreviation = dotlessAbbreviation.intern(); this.shortestUniqueAbbreviation = shortestUniqueAbbreviation.trim().intern(); } public String getName() { return name; } public String getAbbreviation() { return abbreviation; } public String getShortestUniqueAbbreviation() { if (shortestUniqueAbbreviation.isEmpty()) { shortestUniqueAbbreviation = getAbbreviation(); } return shortestUniqueAbbreviation; } public boolean isDefaultShortestUniqueAbbreviation() { return (shortestUniqueAbbreviation.isEmpty()) || this.shortestUniqueAbbreviation.equals(this.abbreviation); } public String getDotlessAbbreviation() { return this.dotlessAbbreviation; } @Override public int compareTo(Abbreviation toCompare) { int nameComparison = getName().compareTo(toCompare.getName()); if (nameComparison != 0) { return nameComparison; } int abbreviationComparison = getAbbreviation().compareTo(toCompare.getAbbreviation()); if (abbreviationComparison != 0) { return abbreviationComparison; } return getShortestUniqueAbbreviation().compareTo(toCompare.getShortestUniqueAbbreviation()); } public String getNext(String current) { String currentTrimmed = current.trim(); if (getDotlessAbbreviation().equals(currentTrimmed)) { return getShortestUniqueAbbreviation().equals(getAbbreviation()) ? getName() : getShortestUniqueAbbreviation(); } else if (getShortestUniqueAbbreviation().equals(currentTrimmed) && !getShortestUniqueAbbreviation().equals(getAbbreviation())) { return getName(); } else if (getName().equals(currentTrimmed)) { return getAbbreviation(); } else { return getDotlessAbbreviation(); } } @Override public String toString() { return String.format("Abbreviation{name=%s, abbreviation=%s, dotlessAbbreviation=%s, shortestUniqueAbbreviation=%s}", this.name, this.abbreviation, this.dotlessAbbreviation, this.shortestUniqueAbbreviation); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Abbreviation that = (Abbreviation) o; return getName().equals(that.getName()) && getAbbreviation().equals(that.getAbbreviation()) && getShortestUniqueAbbreviation().equals(that.getShortestUniqueAbbreviation()); } @Override public int hashCode() { return Objects.hash(getName(), getAbbreviation(), getShortestUniqueAbbreviation()); } }
3,961
33.754386
180
java
null
jabref-main/buildSrc/src/main/java/org/jabref/logic/journals/AbbreviationFormat.java
package org.jabref.logic.journals; import org.apache.commons.csv.CSVFormat; public final class AbbreviationFormat { public static final char DELIMITER = ';'; public static final char ESCAPE = '\\'; public static final char QUOTE = '"'; private AbbreviationFormat() { } public static CSVFormat getCSVFormat() { return CSVFormat.DEFAULT.builder() .setIgnoreEmptyLines(true) .setDelimiter(DELIMITER) .setEscape(ESCAPE) .setQuote(QUOTE) .setTrim(true) .build(); } }
599
24
45
java
null
jabref-main/buildSrc/src/main/java/org/jabref/logic/journals/AbbreviationParser.java
package org.jabref.logic.journals; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collection; import java.util.LinkedHashSet; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Reads abbreviation files (CSV format) into a list of Abbreviations. */ public class AbbreviationParser { private static final Logger LOGGER = LoggerFactory.getLogger(AbbreviationParser.class); // Ensures ordering while preventing duplicates private final LinkedHashSet<Abbreviation> abbreviations = new LinkedHashSet<>(); void readJournalListFromResource(String resourceFileName) { try (InputStream stream = JournalAbbreviationRepository.class.getResourceAsStream(resourceFileName); BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) { readJournalList(reader); } catch (IOException e) { LOGGER.error(String.format("Could not read journal list from file %s", resourceFileName), e); } } public void readJournalListFromFile(Path file) throws IOException { readJournalListFromFile(file, StandardCharsets.UTF_8); } public void readJournalListFromFile(Path file, Charset encoding) throws IOException { try (BufferedReader reader = Files.newBufferedReader(file, encoding)) { readJournalList(reader); } } /** * Read the given file, which should contain a list of journal names and their abbreviations. Each line should be * formatted as: "Full Journal Name;Abbr. Journal Name;[Shortest Unique Abbreviation]" * * @param reader a given file into a Reader object */ private void readJournalList(Reader reader) throws IOException { try (CSVParser csvParser = new CSVParser(reader, AbbreviationFormat.getCSVFormat())) { for (CSVRecord csvRecord : csvParser) { String name = csvRecord.size() > 0 ? csvRecord.get(0) : ""; String abbreviation = csvRecord.size() > 1 ? csvRecord.get(1) : ""; String shortestUniqueAbbreviation = csvRecord.size() > 2 ? csvRecord.get(2) : ""; // Check name and abbreviation if (name.isEmpty() || abbreviation.isEmpty()) { return; } Abbreviation abbreviationToAdd = new Abbreviation(name, abbreviation, shortestUniqueAbbreviation); abbreviations.add(abbreviationToAdd); } } } public Collection<Abbreviation> getAbbreviations() { return abbreviations; } }
2,919
36.922078
117
java
null
jabref-main/buildSrc/src/main/java/org/jabref/logic/journals/AbbreviationWriter.java
package org.jabref.logic.journals; import java.io.IOException; import java.io.OutputStreamWriter; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import org.apache.commons.csv.CSVPrinter; /** * This class provides handy static methods to save abbreviations to the file system. */ public final class AbbreviationWriter { private AbbreviationWriter() { } /** * This method will write the list of abbreviations to a file on the file system specified by the given path. If the * file already exists its content will be overridden, otherwise a new file will be created. * * @param path to a file (doesn't have to exist just yet) * @param abbreviations as a list specifying which entries should be written */ public static void writeOrCreate(Path path, List<Abbreviation> abbreviations) throws IOException { try (OutputStreamWriter writer = new OutputStreamWriter(Files.newOutputStream(path), StandardCharsets.UTF_8); CSVPrinter csvPrinter = new CSVPrinter(writer, AbbreviationFormat.getCSVFormat())) { for (Abbreviation entry : abbreviations) { if (entry.isDefaultShortestUniqueAbbreviation()) { csvPrinter.printRecord(entry.getName(), entry.getAbbreviation()); } else { csvPrinter.printRecord(entry.getName(), entry.getAbbreviation(), entry.getShortestUniqueAbbreviation()); } } } } }
1,560
38.025
124
java
null
jabref-main/buildSrc/src/main/java/org/jabref/logic/journals/JournalAbbreviationLoader.java
package org.jabref.logic.journals; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collection; import java.util.Collections; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p> * This class loads abbreviations from a CSV file and stores them into a MV file * </p> * <p> * Abbreviations are available at <a href="https://github.com/JabRef/abbrv.jabref.org/">https://github.com/JabRef/abbrv.jabref.org/</a>. * </p> */ public class JournalAbbreviationLoader { private static final Logger LOGGER = LoggerFactory.getLogger(JournalAbbreviationLoader.class); public static Collection<Abbreviation> readJournalListFromFile(Path file) throws IOException { LOGGER.debug(String.format("Reading journal list from file %s", file)); AbbreviationParser parser = new AbbreviationParser(); parser.readJournalListFromFile(file); return parser.getAbbreviations(); } public static JournalAbbreviationRepository loadRepository(JournalAbbreviationPreferences journalAbbreviationPreferences) { JournalAbbreviationRepository repository; // Initialize with built-in list try { Path tempDir = Files.createTempDirectory("jabref-journal"); Path tempJournalList = tempDir.resolve("journal-list.mv"); Files.copy(JournalAbbreviationRepository.class.getResourceAsStream("/journals/journal-list.mv"), tempJournalList); repository = new JournalAbbreviationRepository(tempJournalList); tempDir.toFile().deleteOnExit(); tempJournalList.toFile().deleteOnExit(); } catch (IOException e) { LOGGER.error("Error while copying journal list", e); return null; } // Read external lists List<String> lists = journalAbbreviationPreferences.getExternalJournalLists(); if (!(lists.isEmpty())) { // reversing ensures that the latest lists overwrites the former one Collections.reverse(lists); for (String filename : lists) { try { repository.addCustomAbbreviations(readJournalListFromFile(Path.of(filename))); } catch (IOException e) { LOGGER.error("Cannot read external journal list file {}", filename, e); } } } return repository; } public static JournalAbbreviationRepository loadBuiltInRepository() { return loadRepository(new JournalAbbreviationPreferences(Collections.emptyList(), true)); } }
2,639
38.402985
138
java
null
jabref-main/buildSrc/src/main/java/org/jabref/logic/journals/JournalAbbreviationPreferences.java
package org.jabref.logic.journals; import java.util.List; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; public class JournalAbbreviationPreferences { private final ObservableList<String> externalJournalLists; private final BooleanProperty useFJournalField; public JournalAbbreviationPreferences(List<String> externalJournalLists, boolean useFJournalField) { this.externalJournalLists = FXCollections.observableArrayList(externalJournalLists); this.useFJournalField = new SimpleBooleanProperty(useFJournalField); } public ObservableList<String> getExternalJournalLists() { return externalJournalLists; } public void setExternalJournalLists(List<String> list) { externalJournalLists.clear(); externalJournalLists.addAll(list); } public boolean shouldUseFJournalField() { return useFJournalField.get(); } public BooleanProperty useFJournalFieldProperty() { return useFJournalField; } public void setUseFJournalField(boolean useFJournalField) { this.useFJournalField.set(useFJournalField); } }
1,297
29.904762
92
java
null
jabref-main/buildSrc/src/main/java/org/jabref/logic/journals/JournalAbbreviationRepository.java
package org.jabref.logic.journals; import java.nio.file.Path; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.h2.mvstore.MVMap; import org.h2.mvstore.MVStore; /** * A repository for all journal abbreviations, including add and find methods. */ public class JournalAbbreviationRepository { static final Pattern QUESTION_MARK = Pattern.compile("\\?"); private final Map<String, Abbreviation> fullToAbbreviationObject = new HashMap<>(); private final Map<String, Abbreviation> abbreviationToAbbreviationObject = new HashMap<>(); private final Map<String, Abbreviation> dotlessToAbbreviationObject = new HashMap<>(); private final Map<String, Abbreviation> shortestUniqueToAbbreviationObject = new HashMap<>(); private final TreeSet<Abbreviation> customAbbreviations = new TreeSet<>(); public JournalAbbreviationRepository(Path journalList) { MVStore store = new MVStore.Builder().readOnly().fileName(journalList.toAbsolutePath().toString()).open(); MVMap<String, Abbreviation> mvFullToAbbreviationObject = store.openMap("FullToAbbreviation"); mvFullToAbbreviationObject.forEach((name, abbreviation) -> { String abbrevationString = abbreviation.getAbbreviation(); String shortestUniqueAbbreviation = abbreviation.getShortestUniqueAbbreviation(); Abbreviation newAbbreviation = new Abbreviation( name, abbrevationString, shortestUniqueAbbreviation ); fullToAbbreviationObject.put(name, newAbbreviation); abbreviationToAbbreviationObject.put(abbrevationString, newAbbreviation); dotlessToAbbreviationObject.put(newAbbreviation.getDotlessAbbreviation(), newAbbreviation); shortestUniqueToAbbreviationObject.put(shortestUniqueAbbreviation, newAbbreviation); }); } private static boolean isMatched(String name, Abbreviation abbreviation) { return name.equalsIgnoreCase(abbreviation.getName()) || name.equalsIgnoreCase(abbreviation.getAbbreviation()) || name.equalsIgnoreCase(abbreviation.getDotlessAbbreviation()) || name.equalsIgnoreCase(abbreviation.getShortestUniqueAbbreviation()); } private static boolean isMatchedAbbreviated(String name, Abbreviation abbreviation) { boolean isExpanded = name.equalsIgnoreCase(abbreviation.getName()); if (isExpanded) { return false; } boolean isAbbreviated = name.equalsIgnoreCase(abbreviation.getAbbreviation()) || name.equalsIgnoreCase(abbreviation.getDotlessAbbreviation()) || name.equalsIgnoreCase(abbreviation.getShortestUniqueAbbreviation()); return isAbbreviated; } /** * Returns true if the given journal name is contained in the list either in its full form * (e.g., Physical Review Letters) or its abbreviated form (e.g., Phys. Rev. Lett.). */ public boolean isKnownName(String journalName) { if (QUESTION_MARK.matcher(journalName).find()) { return false; } String journal = journalName.trim().replaceAll(Matcher.quoteReplacement("\\&"), "&"); return customAbbreviations.stream().anyMatch(abbreviation -> isMatched(journal, abbreviation)) || fullToAbbreviationObject.containsKey(journal) || abbreviationToAbbreviationObject.containsKey(journal) || dotlessToAbbreviationObject.containsKey(journal) || shortestUniqueToAbbreviationObject.containsKey(journal); } /** * Returns true if the given journal name is in its abbreviated form (e.g. Phys. Rev. Lett.). The test is strict, * i.e., journals whose abbreviation is the same as the full name are not considered */ public boolean isAbbreviatedName(String journalName) { if (QUESTION_MARK.matcher(journalName).find()) { return false; } String journal = journalName.trim().replaceAll(Matcher.quoteReplacement("\\&"), "&"); return customAbbreviations.stream().anyMatch(abbreviation -> isMatchedAbbreviated(journal, abbreviation)) || abbreviationToAbbreviationObject.containsKey(journal) || dotlessToAbbreviationObject.containsKey(journal) || shortestUniqueToAbbreviationObject.containsKey(journal); } /** * Attempts to get the abbreviation of the journal given. * * @param input The journal name (either full name or abbreviated name). */ public Optional<Abbreviation> get(String input) { // Clean up input: trim and unescape ampersand String journal = input.trim().replaceAll(Matcher.quoteReplacement("\\&"), "&"); Optional<Abbreviation> customAbbreviation = customAbbreviations.stream() .filter(abbreviation -> isMatched(journal, abbreviation)) .findFirst(); if (customAbbreviation.isPresent()) { return customAbbreviation; } return Optional.ofNullable(fullToAbbreviationObject.get(journal)) .or(() -> Optional.ofNullable(abbreviationToAbbreviationObject.get(journal))) .or(() -> Optional.ofNullable(dotlessToAbbreviationObject.get(journal))) .or(() -> Optional.ofNullable(shortestUniqueToAbbreviationObject.get(journal))); } public void addCustomAbbreviation(Abbreviation abbreviation) { Objects.requireNonNull(abbreviation); // We do NOT want to keep duplicates // The set automatically "removes" duplicates // What is a duplicate? An abbreviation is NOT the same if any field is NOT equal (e.g., if the shortest unique differs, the abbreviation is NOT the same) customAbbreviations.add(abbreviation); } public Collection<Abbreviation> getCustomAbbreviations() { return customAbbreviations; } public void addCustomAbbreviations(Collection<Abbreviation> abbreviationsToAdd) { abbreviationsToAdd.forEach(this::addCustomAbbreviation); } public Optional<String> getNextAbbreviation(String text) { return get(text).map(abbreviation -> abbreviation.getNext(text)); } public Optional<String> getDefaultAbbreviation(String text) { return get(text).map(Abbreviation::getAbbreviation); } public Optional<String> getDotless(String text) { return get(text).map(Abbreviation::getDotlessAbbreviation); } public Optional<String> getShortestUniqueAbbreviation(String text) { return get(text).map(Abbreviation::getShortestUniqueAbbreviation); } public Set<String> getFullNames() { return fullToAbbreviationObject.keySet(); } public Collection<Abbreviation> getAllLoaded() { return fullToAbbreviationObject.values(); } }
7,212
44.08125
162
java
null
jabref-main/buildSrc/src/main/java/org/jabref/logic/journals/package-info.java
/** * This code is copied from src/main/java/org/jabref/logic/journals */ package org.jabref.logic.journals;
111
21.4
67
java
null
jabref-main/src/jmh/java/org/jabref/benchmarks/Benchmarks.java
package org.jabref.benchmarks; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.util.EnumSet; import java.util.List; import java.util.Random; import java.util.stream.Collectors; import org.jabref.gui.Globals; import org.jabref.logic.bibtex.FieldPreferences; import org.jabref.logic.citationkeypattern.CitationKeyPatternPreferences; import org.jabref.logic.exporter.BibWriter; import org.jabref.logic.exporter.BibtexDatabaseWriter; import org.jabref.logic.exporter.SaveConfiguration; import org.jabref.logic.formatter.bibtexfields.HtmlToLatexFormatter; import org.jabref.logic.importer.ParserResult; import org.jabref.logic.importer.fileformat.BibtexParser; import org.jabref.logic.layout.format.HTMLChars; import org.jabref.logic.layout.format.LatexToUnicodeFormatter; import org.jabref.logic.search.SearchQuery; import org.jabref.logic.util.OS; import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.database.BibDatabaseMode; import org.jabref.model.database.BibDatabaseModeDetection; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.BibEntryTypesManager; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.field.UnknownField; import org.jabref.model.groups.GroupHierarchyType; import org.jabref.model.groups.KeywordGroup; import org.jabref.model.groups.WordKeywordGroup; import org.jabref.model.metadata.MetaData; import org.jabref.model.search.rules.SearchRules.SearchFlags; import org.jabref.preferences.JabRefPreferences; import org.openjdk.jmh.Main; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.runner.RunnerException; import static org.mockito.Mockito.mock; @State(Scope.Thread) public class Benchmarks { private String bibtexString; private final BibDatabase database = new BibDatabase(); private String latexConversionString; private String htmlConversionString; @Setup public void init() throws Exception { Globals.prefs = JabRefPreferences.getInstance(); Random randomizer = new Random(); for (int i = 0; i < 1000; i++) { BibEntry entry = new BibEntry(); entry.setCitationKey("id" + i); entry.setField(StandardField.TITLE, "This is my title " + i); entry.setField(StandardField.AUTHOR, "Firstname Lastname and FirstnameA LastnameA and FirstnameB LastnameB" + i); entry.setField(StandardField.JOURNAL, "Journal Title " + i); entry.setField(StandardField.KEYWORDS, "testkeyword"); entry.setField(StandardField.YEAR, "1" + i); entry.setField(new UnknownField("rnd"), "2" + randomizer.nextInt()); database.insertEntry(entry); } bibtexString = getOutputWriter().toString(); latexConversionString = "{A} \\textbf{bold} approach {\\it to} ${{\\Sigma}}{\\Delta}$ modulator \\textsuperscript{2} \\$"; htmlConversionString = "<b>&Ouml;sterreich</b> &#8211; &amp; characters &#x2aa2; <i>italic</i>"; } private StringWriter getOutputWriter() throws IOException { StringWriter outputWriter = new StringWriter(); BibWriter bibWriter = new BibWriter(outputWriter, OS.NEWLINE); BibtexDatabaseWriter databaseWriter = new BibtexDatabaseWriter( bibWriter, mock(SaveConfiguration.class), mock(FieldPreferences.class), mock(CitationKeyPatternPreferences.class), new BibEntryTypesManager()); databaseWriter.savePartOfDatabase(new BibDatabaseContext(database, new MetaData()), database.getEntries()); return outputWriter; } @Benchmark public ParserResult parse() throws IOException { BibtexParser parser = new BibtexParser(Globals.prefs.getImportFormatPreferences()); return parser.parse(new StringReader(bibtexString)); } @Benchmark public String write() throws Exception { return getOutputWriter().toString(); } @Benchmark public List<BibEntry> search() { // FIXME: Reuse SearchWorker here SearchQuery searchQuery = new SearchQuery("Journal Title 500", EnumSet.noneOf(SearchFlags.class)); return database.getEntries().stream().filter(searchQuery::isMatch).collect(Collectors.toList()); } @Benchmark public List<BibEntry> parallelSearch() { // FIXME: Reuse SearchWorker here SearchQuery searchQuery = new SearchQuery("Journal Title 500", EnumSet.noneOf(SearchFlags.class)); return database.getEntries().parallelStream().filter(searchQuery::isMatch).collect(Collectors.toList()); } @Benchmark public BibDatabaseMode inferBibDatabaseMode() { return BibDatabaseModeDetection.inferMode(database); } @Benchmark public String latexToUnicodeConversion() { LatexToUnicodeFormatter f = new LatexToUnicodeFormatter(); return f.format(latexConversionString); } @Benchmark public String latexToHTMLConversion() { HTMLChars f = new HTMLChars(); return f.format(latexConversionString); } @Benchmark public String htmlToLatexConversion() { HtmlToLatexFormatter f = new HtmlToLatexFormatter(); return f.format(htmlConversionString); } @Benchmark public boolean keywordGroupContains() { KeywordGroup group = new WordKeywordGroup("testGroup", GroupHierarchyType.INDEPENDENT, StandardField.KEYWORDS, "testkeyword", false, ',', false); return group.containsAll(database.getEntries()); } public static void main(String[] args) throws IOException, RunnerException { Main.main(args); } }
5,882
37.960265
153
java
null
jabref-main/src/main/java/module-info.java
open module org.jabref { // Swing requires java.desktop; // SQL requires java.sql; requires java.sql.rowset; // JavaFX requires javafx.base; requires javafx.graphics; requires javafx.controls; requires javafx.web; requires javafx.fxml; requires afterburner.fx; requires com.dlsc.gemsfx; uses com.dlsc.gemsfx.TagsField; requires de.saxsys.mvvmfx; requires org.kordamp.ikonli.core; requires org.kordamp.ikonli.javafx; requires org.kordamp.ikonli.materialdesign2; uses org.kordamp.ikonli.IkonHandler; uses org.kordamp.ikonli.IkonProvider; provides org.kordamp.ikonli.IkonHandler with org.jabref.gui.icon.JabRefIkonHandler; provides org.kordamp.ikonli.IkonProvider with org.jabref.gui.icon.JabrefIconProvider; requires org.controlsfx.controls; requires org.fxmisc.richtext; requires com.tobiasdiez.easybind; provides com.airhacks.afterburner.views.ResourceLocator with org.jabref.gui.util.JabRefResourceLocator; provides com.airhacks.afterburner.injection.PresenterFactory with org.jabref.gui.DefaultInjector; // Logging requires org.slf4j; requires org.tinylog.api; requires org.tinylog.api.slf4j; requires org.tinylog.impl; provides org.tinylog.writers.Writer with org.jabref.gui.logging.GuiWriter, org.jabref.gui.logging.ApplicationInsightsWriter; // Preferences and XML requires java.prefs; requires jakarta.xml.bind; // needs to be loaded here as it's otherwise not found at runtime requires org.glassfish.jaxb.runtime; requires jdk.xml.dom; // Annotations (@PostConstruct) requires jakarta.annotation; // Microsoft application insights requires applicationinsights.core; requires applicationinsights.logging.log4j2; // Libre Office requires org.libreoffice.uno; // Other modules requires com.google.common; requires jakarta.inject; requires reactfx; requires commons.cli; requires com.github.tomtung.latex2unicode; requires fastparse; requires jbibtex; requires citeproc.java; requires de.saxsys.mvvmfx.validation; requires com.google.gson; requires unirest.java; requires org.apache.httpcomponents.httpclient; requires org.jsoup; requires org.apache.commons.csv; requires io.github.javadiffutils; requires java.string.similarity; requires ojdbc10; requires org.postgresql.jdbc; requires org.mariadb.jdbc; uses org.mariadb.jdbc.credential.CredentialPlugin; requires org.apache.commons.lang3; requires org.antlr.antlr4.runtime; requires org.fxmisc.flowless; requires pdfbox; requires xmpbox; requires com.ibm.icu; requires flexmark; requires flexmark.util.ast; requires flexmark.util.data; requires com.h2database.mvstore; requires java.keyring; requires org.jooq.jool; // fulltext search requires org.apache.lucene.core; // In case the version is updated, please also adapt SearchFieldConstants#VERSION to the newly used version uses org.apache.lucene.codecs.lucene95.Lucene95Codec; requires org.apache.lucene.queryparser; uses org.apache.lucene.queryparser.classic.MultiFieldQueryParser; requires org.apache.lucene.analysis.common; requires org.apache.lucene.highlighter; requires com.fasterxml.jackson.databind; requires com.fasterxml.jackson.dataformat.yaml; requires com.fasterxml.jackson.datatype.jsr310; requires net.harawata.appdirs; requires com.sun.jna; requires com.sun.jna.platform; requires org.eclipse.jgit; uses org.eclipse.jgit.transport.SshSessionFactory; uses org.eclipse.jgit.lib.GpgSigner; }
3,780
28.771654
111
java
null
jabref-main/src/main/java/org/jabref/architecture/AllowedToUseAwt.java
package org.jabref.architecture; /** * Annotation to indicate that this logic class can access AWT */ public @interface AllowedToUseAwt { // The rationale String value(); }
185
15.909091
62
java
null
jabref-main/src/main/java/org/jabref/architecture/AllowedToUseLogic.java
package org.jabref.architecture; /** * Annotation to indicate that this logic class can be used in the model package. */ public @interface AllowedToUseLogic { // The rationale String value(); }
206
17.818182
81
java
null
jabref-main/src/main/java/org/jabref/architecture/AllowedToUseStandardStreams.java
package org.jabref.architecture; /** * Annotation to indicate that this class can use System.Out.* instead of using the logging framework */ public @interface AllowedToUseStandardStreams { // The rationale String value(); }
236
20.545455
101
java
null
jabref-main/src/main/java/org/jabref/architecture/AllowedToUseSwing.java
package org.jabref.architecture; /** * Annotation to indicate that this logic class can access swing */ public @interface AllowedToUseSwing { // The rationale String value(); }
189
16.272727
64
java
null
jabref-main/src/main/java/org/jabref/architecture/ApacheCommonsLang3Allowed.java
package org.jabref.architecture; /** * Annotation to indicate that usage of ApacheCommonsLang3 is explicitly allowed. * The intention is to fully switch to Google Guava and only use Apache Commons Lang3 if there is no other possibility */ public @interface ApacheCommonsLang3Allowed { // The rationale String value(); }
333
26.833333
118
java
null
jabref-main/src/main/java/org/jabref/cli/ArgumentProcessor.java
package org.jabref.cli; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Optional; import java.util.Set; import java.util.prefs.BackingStoreException; import org.jabref.gui.Globals; import org.jabref.gui.externalfiles.AutoSetFileLinksUtil; import org.jabref.gui.undo.NamedCompound; import org.jabref.logic.JabRefException; import org.jabref.logic.bibtex.FieldPreferences; import org.jabref.logic.citationkeypattern.CitationKeyGenerator; import org.jabref.logic.exporter.AtomicFileWriter; import org.jabref.logic.exporter.BibDatabaseWriter; import org.jabref.logic.exporter.BibWriter; import org.jabref.logic.exporter.BibtexDatabaseWriter; import org.jabref.logic.exporter.EmbeddedBibFilePdfExporter; import org.jabref.logic.exporter.Exporter; import org.jabref.logic.exporter.ExporterFactory; import org.jabref.logic.exporter.SaveConfiguration; import org.jabref.logic.exporter.XmpPdfExporter; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.ImportException; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.ImportFormatReader; import org.jabref.logic.importer.OpenDatabase; import org.jabref.logic.importer.OutputPrinter; import org.jabref.logic.importer.ParseException; import org.jabref.logic.importer.ParserResult; import org.jabref.logic.importer.SearchBasedFetcher; import org.jabref.logic.importer.WebFetchers; import org.jabref.logic.importer.fileformat.BibtexParser; import org.jabref.logic.journals.JournalAbbreviationRepository; import org.jabref.logic.l10n.Localization; import org.jabref.logic.net.URLDownload; import org.jabref.logic.search.DatabaseSearcher; import org.jabref.logic.search.SearchQuery; import org.jabref.logic.shared.prefs.SharedDatabasePreferences; import org.jabref.logic.util.OS; import org.jabref.logic.util.io.FileUtil; import org.jabref.logic.xmp.XmpPreferences; import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.database.BibDatabaseMode; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.BibEntryTypesManager; import org.jabref.model.strings.StringUtil; import org.jabref.model.util.DummyFileUpdateMonitor; import org.jabref.model.util.FileUpdateMonitor; import org.jabref.preferences.FilePreferences; import org.jabref.preferences.PreferencesService; import org.jabref.preferences.SearchPreferences; import com.google.common.base.Throwables; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ArgumentProcessor { private static final Logger LOGGER = LoggerFactory.getLogger(ArgumentProcessor.class); private final JabRefCLI cli; private final List<ParserResult> parserResults; private final Mode startupMode; private final PreferencesService preferencesService; private final FileUpdateMonitor fileUpdateMonitor; private boolean noGUINeeded; public ArgumentProcessor(String[] args, Mode startupMode, PreferencesService preferencesService, FileUpdateMonitor fileUpdateMonitor) throws org.apache.commons.cli.ParseException { this.cli = new JabRefCLI(args); this.startupMode = startupMode; this.preferencesService = preferencesService; this.fileUpdateMonitor = fileUpdateMonitor; this.parserResults = processArguments(); } /** * Will open a file (like importFile), but will also request JabRef to focus on this database * * @param argument See importFile. * @return ParserResult with setToOpenTab(true) */ private Optional<ParserResult> importToOpenBase(String argument) { Optional<ParserResult> result = importFile(argument); result.ifPresent(ParserResult::setToOpenTab); return result; } private Optional<ParserResult> importBibtexToOpenBase(String argument, ImportFormatPreferences importFormatPreferences) { BibtexParser parser = new BibtexParser(importFormatPreferences); try { List<BibEntry> entries = parser.parseEntries(argument); ParserResult result = new ParserResult(entries); result.setToOpenTab(); return Optional.of(result); } catch (ParseException e) { System.err.println(Localization.lang("Error occurred when parsing entry") + ": " + e.getLocalizedMessage()); return Optional.empty(); } } private Optional<ParserResult> importFile(String argument) { String[] data = argument.split(","); String address = data[0]; Path file; if (address.startsWith("http://") || address.startsWith("https://") || address.startsWith("ftp://")) { // Download web resource to temporary file try { file = new URLDownload(address).toTemporaryFile(); } catch (IOException e) { System.err.println(Localization.lang("Problem downloading from %1", address) + e.getLocalizedMessage()); return Optional.empty(); } } else { if (OS.WINDOWS) { file = Path.of(address); } else { file = Path.of(address.replace("~", System.getProperty("user.home"))); } } String importFormat; if (data.length > 1) { importFormat = data[1]; } else { importFormat = "*"; } Optional<ParserResult> importResult = importFile(file, importFormat); importResult.ifPresent(result -> { OutputPrinter printer = new SystemOutputPrinter(); if (result.hasWarnings()) { printer.showMessage(result.getErrorMessage()); } }); return importResult; } private Optional<ParserResult> importFile(Path file, String importFormat) { try { ImportFormatReader importFormatReader = new ImportFormatReader( preferencesService.getImporterPreferences(), preferencesService.getImportFormatPreferences(), fileUpdateMonitor); if (!"*".equals(importFormat)) { System.out.println(Localization.lang("Importing") + ": " + file); ParserResult result = importFormatReader.importFromFile(importFormat, file); return Optional.of(result); } else { // * means "guess the format": System.out.println(Localization.lang("Importing in unknown format") + ": " + file); ImportFormatReader.UnknownFormatImport importResult = importFormatReader.importUnknownFormat(file, new DummyFileUpdateMonitor()); System.out.println(Localization.lang("Format used") + ": " + importResult.format()); return Optional.of(importResult.parserResult()); } } catch (ImportException ex) { System.err .println(Localization.lang("Error opening file") + " '" + file + "': " + ex.getLocalizedMessage()); return Optional.empty(); } } public List<ParserResult> getParserResults() { return parserResults; } public boolean hasParserResults() { return !parserResults.isEmpty(); } private List<ParserResult> processArguments() { if (!cli.isBlank() && cli.isDebugLogging()) { System.err.println("use java property -Dtinylog.level=debug"); } if ((startupMode == Mode.INITIAL_START) && cli.isShowVersion()) { cli.displayVersion(); } if ((startupMode == Mode.INITIAL_START) && cli.isHelp()) { JabRefCLI.printUsage(preferencesService); noGUINeeded = true; return Collections.emptyList(); } // Check if we should reset all preferences to default values: if (cli.isPreferencesReset()) { resetPreferences(cli.getPreferencesReset()); } // Check if we should import preferences from a file: if (cli.isPreferencesImport()) { importPreferences(); } // List to put imported/loaded database(s) in. List<ParserResult> loaded = importAndOpenFiles(); if (!cli.isBlank() && cli.isFetcherEngine()) { fetch(cli.getFetcherEngine()).ifPresent(loaded::add); } if (cli.isExportMatches()) { if (!loaded.isEmpty()) { if (!exportMatches(loaded)) { return Collections.emptyList(); } } else { System.err.println(Localization.lang("The output option depends on a valid input option.")); } } if (cli.isGenerateCitationKeys()) { regenerateCitationKeys(loaded); } if (cli.isAutomaticallySetFileLinks()) { automaticallySetFileLinks(loaded); } if ((cli.isWriteXMPtoPdf() && cli.isEmbeddBibfileInPdf()) || (cli.isWriteMetadatatoPdf() && (cli.isWriteXMPtoPdf() || cli.isEmbeddBibfileInPdf()))) { System.err.println("Give only one of [writeXMPtoPdf, embeddBibfileInPdf, writeMetadatatoPdf]"); } if (cli.isWriteMetadatatoPdf() || cli.isWriteXMPtoPdf() || cli.isEmbeddBibfileInPdf()) { if (!loaded.isEmpty()) { writeMetadataToPdf(loaded, cli.getWriteMetadatatoPdf(), preferencesService.getXmpPreferences(), preferencesService.getFilePreferences(), preferencesService.getLibraryPreferences().getDefaultBibDatabaseMode(), Globals.entryTypesManager, preferencesService.getFieldPreferences(), Globals.journalAbbreviationRepository, cli.isWriteXMPtoPdf() || cli.isWriteMetadatatoPdf(), cli.isEmbeddBibfileInPdf() || cli.isWriteMetadatatoPdf()); } } if (cli.isFileExport()) { if (!loaded.isEmpty()) { exportFile(loaded, cli.getFileExport().split(",")); LOGGER.debug("Finished export"); } else { System.err.println(Localization.lang("The output option depends on a valid import option.")); } } if (cli.isPreferencesExport()) { try { preferencesService.exportPreferences(Path.of(cli.getPreferencesExport())); } catch (JabRefException ex) { LOGGER.error("Cannot export preferences", ex); } } if (!cli.isBlank() && cli.isAuxImport()) { doAuxImport(loaded); } return loaded; } private void writeMetadataToPdf(List<ParserResult> loaded, String filesAndCitekeys, XmpPreferences xmpPreferences, FilePreferences filePreferences, BibDatabaseMode databaseMode, BibEntryTypesManager entryTypesManager, FieldPreferences fieldPreferences, JournalAbbreviationRepository abbreviationRepository, boolean writeXMP, boolean embeddBibfile) { if (loaded.isEmpty()) { LOGGER.error("The write xmp option depends on a valid import option."); return; } ParserResult pr = loaded.get(loaded.size() - 1); BibDatabaseContext databaseContext = pr.getDatabaseContext(); BibDatabase dataBase = pr.getDatabase(); XmpPdfExporter xmpPdfExporter = new XmpPdfExporter(xmpPreferences); EmbeddedBibFilePdfExporter embeddedBibFilePdfExporter = new EmbeddedBibFilePdfExporter(databaseMode, entryTypesManager, fieldPreferences); if ("all".equals(filesAndCitekeys)) { for (BibEntry entry : dataBase.getEntries()) { writeMetadataToPDFsOfEntry( databaseContext, entry.getCitationKey().orElse("<no cite key defined>"), entry, filePreferences, xmpPdfExporter, embeddedBibFilePdfExporter, abbreviationRepository, writeXMP, embeddBibfile); } return; } List<String> citeKeys = new ArrayList<>(); List<String> pdfs = new ArrayList<>(); for (String fileOrCiteKey : filesAndCitekeys.split(",")) { if (fileOrCiteKey.toLowerCase(Locale.ROOT).endsWith(".pdf")) { pdfs.add(fileOrCiteKey); } else { citeKeys.add(fileOrCiteKey); } } writeMetadataToPdfByCitekey( databaseContext, dataBase, citeKeys, filePreferences, xmpPdfExporter, embeddedBibFilePdfExporter, abbreviationRepository, writeXMP, embeddBibfile); writeMetadataToPdfByFileNames( databaseContext, dataBase, pdfs, filePreferences, xmpPdfExporter, embeddedBibFilePdfExporter, abbreviationRepository, writeXMP, embeddBibfile); } private void writeMetadataToPDFsOfEntry(BibDatabaseContext databaseContext, String citeKey, BibEntry entry, FilePreferences filePreferences, XmpPdfExporter xmpPdfExporter, EmbeddedBibFilePdfExporter embeddedBibFilePdfExporter, JournalAbbreviationRepository abbreviationRepository, boolean writeXMP, boolean embeddBibfile) { try { if (writeXMP) { if (xmpPdfExporter.exportToAllFilesOfEntry(databaseContext, filePreferences, entry, List.of(entry), abbreviationRepository)) { System.out.printf("Successfully written XMP metadata on at least one linked file of %s%n", citeKey); } else { System.err.printf("Cannot write XMP metadata on any linked files of %s. Make sure there is at least one linked file and the path is correct.%n", citeKey); } } if (embeddBibfile) { if (embeddedBibFilePdfExporter.exportToAllFilesOfEntry(databaseContext, filePreferences, entry, List.of(entry), abbreviationRepository)) { System.out.printf("Successfully embedded metadata on at least one linked file of %s%n", citeKey); } else { System.out.printf("Cannot embedd metadata on any linked files of %s. Make sure there is at least one linked file and the path is correct.%n", citeKey); } } } catch (Exception e) { LOGGER.error("Failed writing metadata on a linked file of {}.", citeKey); } } private void writeMetadataToPdfByCitekey(BibDatabaseContext databaseContext, BibDatabase dataBase, List<String> citeKeys, FilePreferences filePreferences, XmpPdfExporter xmpPdfExporter, EmbeddedBibFilePdfExporter embeddedBibFilePdfExporter, JournalAbbreviationRepository abbreviationRepository, boolean writeXMP, boolean embeddBibfile) { for (String citeKey : citeKeys) { List<BibEntry> bibEntryList = dataBase.getEntriesByCitationKey(citeKey); if (bibEntryList.isEmpty()) { System.err.printf("Skipped - Cannot find %s in library.%n", citeKey); continue; } for (BibEntry entry : bibEntryList) { writeMetadataToPDFsOfEntry(databaseContext, citeKey, entry, filePreferences, xmpPdfExporter, embeddedBibFilePdfExporter, abbreviationRepository, writeXMP, embeddBibfile); } } } private void writeMetadataToPdfByFileNames(BibDatabaseContext databaseContext, BibDatabase dataBase, List<String> pdfs, FilePreferences filePreferences, XmpPdfExporter xmpPdfExporter, EmbeddedBibFilePdfExporter embeddedBibFilePdfExporter, JournalAbbreviationRepository abbreviationRepository, boolean writeXMP, boolean embeddBibfile) { for (String fileName : pdfs) { Path filePath = Path.of(fileName); if (!filePath.isAbsolute()) { filePath = FileUtil.find(fileName, databaseContext.getFileDirectories(filePreferences)).orElse(FileUtil.find(fileName, List.of(Path.of("").toAbsolutePath())).orElse(filePath)); } if (Files.exists(filePath)) { try { if (writeXMP) { if (xmpPdfExporter.exportToFileByPath(databaseContext, dataBase, filePreferences, filePath, abbreviationRepository)) { System.out.printf("Successfully written XMP metadata of at least one entry to %s%n", fileName); } else { System.out.printf("File %s is not linked to any entry in database.%n", fileName); } } if (embeddBibfile) { if (embeddedBibFilePdfExporter.exportToFileByPath(databaseContext, dataBase, filePreferences, filePath, abbreviationRepository)) { System.out.printf("Successfully embedded XMP metadata of at least one entry to %s%n", fileName); } else { System.out.printf("File %s is not linked to any entry in database.%n", fileName); } } } catch (IOException e) { LOGGER.error("Error accessing file '{}'.", fileName); } catch (Exception e) { LOGGER.error("Error writing entry to {}.", fileName); } } else { LOGGER.error("Skipped - PDF {} does not exist", fileName); } } } private boolean exportMatches(List<ParserResult> loaded) { String[] data = cli.getExportMatches().split(","); String searchTerm = data[0].replace("\\$", " "); // enables blanks within the search term: // $ stands for a blank ParserResult pr = loaded.get(loaded.size() - 1); BibDatabaseContext databaseContext = pr.getDatabaseContext(); BibDatabase dataBase = pr.getDatabase(); SearchPreferences searchPreferences = preferencesService.getSearchPreferences(); SearchQuery query = new SearchQuery(searchTerm, searchPreferences.getSearchFlags()); List<BibEntry> matches = new DatabaseSearcher(query, dataBase).getMatches(); // export matches if (!matches.isEmpty()) { String formatName; // read in the export format, take default format if no format entered switch (data.length) { case 3 -> formatName = data[2]; case 2 -> // default exporter: bib file formatName = "bib"; default -> { System.err.println(Localization.lang("Output file missing").concat(". \n \t ") .concat(Localization.lang("Usage")).concat(": ") + JabRefCLI.getExportMatchesSyntax()); noGUINeeded = true; return false; } } if ("bib".equals(formatName)) { // output a bib file as default or if // provided exportFormat is "bib" saveDatabase(new BibDatabase(matches), data[1]); LOGGER.debug("Finished export"); } else { // export new database ExporterFactory exporterFactory = ExporterFactory.create( preferencesService, Globals.entryTypesManager); Optional<Exporter> exporter = exporterFactory.getExporterByName(formatName); if (exporter.isEmpty()) { System.err.println(Localization.lang("Unknown export format") + ": " + formatName); } else { // We have an TemplateExporter instance: try { System.out.println(Localization.lang("Exporting") + ": " + data[1]); exporter.get().export(databaseContext, Path.of(data[1]), matches, Collections.emptyList(), Globals.journalAbbreviationRepository); } catch (Exception ex) { System.err.println(Localization.lang("Could not export file") + " '" + data[1] + "': " + Throwables.getStackTraceAsString(ex)); } } } } else { System.err.println(Localization.lang("No search matches.")); } return true; } private void doAuxImport(List<ParserResult> loaded) { boolean usageMsg; if (!loaded.isEmpty()) { usageMsg = generateAux(loaded, cli.getAuxImport().split(",")); } else { usageMsg = true; } if (usageMsg) { System.out.println(Localization.lang("no base-BibTeX-file specified") + "!"); System.out.println(Localization.lang("usage") + " :"); System.out.println("jabref --aux infile[.aux],outfile[.bib] base-BibTeX-file"); } } private List<ParserResult> importAndOpenFiles() { List<ParserResult> loaded = new ArrayList<>(); List<String> toImport = new ArrayList<>(); if (!cli.isBlank() && (!cli.getLeftOver().isEmpty())) { for (String aLeftOver : cli.getLeftOver()) { // Leftover arguments that have a "bib" extension are interpreted as // BIB files to open. Other files, and files that could not be opened // as bib, we try to import instead. boolean bibExtension = aLeftOver.toLowerCase(Locale.ENGLISH).endsWith("bib"); ParserResult pr = new ParserResult(); if (bibExtension) { try { pr = OpenDatabase.loadDatabase( Path.of(aLeftOver), preferencesService.getImportFormatPreferences(), fileUpdateMonitor); } catch (IOException ex) { pr = ParserResult.fromError(ex); LOGGER.error("Error opening file '{}'", aLeftOver, ex); } } if (!bibExtension || (pr.isEmpty())) { // We will try to import this file. Normally we // will import it into a new tab, but if this import has // been initiated by another instance through the remote // listener, we will instead import it into the current library. // This will enable easy integration with web browsers that can // open a reference file in JabRef. if (startupMode == Mode.INITIAL_START) { toImport.add(aLeftOver); } else { loaded.add(importToOpenBase(aLeftOver).orElse(new ParserResult())); } } else { loaded.add(pr); } } } if (!cli.isBlank() && cli.isFileImport()) { toImport.add(cli.getFileImport()); } for (String filenameString : toImport) { importFile(filenameString).ifPresent(loaded::add); } if (!cli.isBlank() && cli.isImportToOpenBase()) { importToOpenBase(cli.getImportToOpenBase()).ifPresent(loaded::add); } if (!cli.isBlank() && cli.isBibtexImport()) { importBibtexToOpenBase(cli.getBibtexImport(), preferencesService.getImportFormatPreferences()).ifPresent(loaded::add); } return loaded; } private boolean generateAux(List<ParserResult> loaded, String[] data) { if (data.length == 2) { ParserResult pr = loaded.get(0); AuxCommandLine acl = new AuxCommandLine(data[0], pr.getDatabase()); BibDatabase newBase = acl.perform(); boolean notSavedMsg = false; // write an output, if something could be resolved if ((newBase != null) && newBase.hasEntries()) { String subName = StringUtil.getCorrectFileName(data[1], "bib"); saveDatabase(newBase, subName); notSavedMsg = true; } if (!notSavedMsg) { System.out.println(Localization.lang("no library generated")); } return false; } else { return true; } } private void saveDatabase(BibDatabase newBase, String subName) { try { System.out.println(Localization.lang("Saving") + ": " + subName); try (AtomicFileWriter fileWriter = new AtomicFileWriter(Path.of(subName), StandardCharsets.UTF_8)) { BibWriter bibWriter = new BibWriter(fileWriter, OS.NEWLINE); SaveConfiguration saveConfiguration = new SaveConfiguration() .withMetadataSaveOrder(true) .withReformatOnSave(preferencesService.getLibraryPreferences().shouldAlwaysReformatOnSave()); BibDatabaseWriter databaseWriter = new BibtexDatabaseWriter( bibWriter, saveConfiguration, preferencesService.getFieldPreferences(), preferencesService.getCitationKeyPatternPreferences(), Globals.entryTypesManager); databaseWriter.saveDatabase(new BibDatabaseContext(newBase)); // Show just a warning message if encoding did not work for all characters: if (fileWriter.hasEncodingProblems()) { System.err.println(Localization.lang("Warning") + ": " + Localization.lang("UTF-8 could not be used to encode the following characters: %0", fileWriter.getEncodingProblems())); } } } catch (IOException ex) { System.err.println(Localization.lang("Could not save file.") + "\n" + ex.getLocalizedMessage()); } } private void exportFile(List<ParserResult> loaded, String[] data) { if (data.length == 1) { // This signals that the latest import should be stored in BibTeX // format to the given file. if (!loaded.isEmpty()) { ParserResult pr = loaded.get(loaded.size() - 1); if (!pr.isInvalid()) { saveDatabase(pr.getDatabase(), data[0]); } } else { System.err.println(Localization.lang("The output option depends on a valid import option.")); } } else if (data.length == 2) { // This signals that the latest import should be stored in the given // format to the given file. ParserResult pr = loaded.get(loaded.size() - 1); Path path = pr.getPath().get().toAbsolutePath(); BibDatabaseContext databaseContext = pr.getDatabaseContext(); databaseContext.setDatabasePath(path); List<Path> fileDirForDatabase = databaseContext .getFileDirectories(preferencesService.getFilePreferences()); System.out.println(Localization.lang("Exporting") + ": " + data[0]); ExporterFactory exporterFactory = ExporterFactory.create( preferencesService, Globals.entryTypesManager); Optional<Exporter> exporter = exporterFactory.getExporterByName(data[1]); if (exporter.isEmpty()) { System.err.println(Localization.lang("Unknown export format") + ": " + data[1]); } else { // We have an exporter: try { exporter.get().export( pr.getDatabaseContext(), Path.of(data[0]), pr.getDatabaseContext().getDatabase().getEntries(), fileDirForDatabase, Globals.journalAbbreviationRepository); } catch (Exception ex) { System.err.println(Localization.lang("Could not export file") + " '" + data[0] + "': " + Throwables.getStackTraceAsString(ex)); } } } } private void importPreferences() { try { preferencesService.importPreferences(Path.of(cli.getPreferencesImport())); Globals.entryTypesManager = preferencesService.getCustomEntryTypesRepository(); } catch (JabRefException ex) { LOGGER.error("Cannot import preferences", ex); } } private void resetPreferences(String value) { if ("all".equals(value.trim())) { try { System.out.println(Localization.lang("Setting all preferences to default values.")); preferencesService.clear(); new SharedDatabasePreferences().clear(); } catch (BackingStoreException e) { System.err.println(Localization.lang("Unable to clear preferences.")); LOGGER.error("Unable to clear preferences", e); } } else { String[] keys = value.split(","); for (String key : keys) { try { preferencesService.deleteKey(key.trim()); System.out.println(Localization.lang("Resetting preference key '%0'", key.trim())); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } } } } private void automaticallySetFileLinks(List<ParserResult> loaded) { for (ParserResult parserResult : loaded) { BibDatabase database = parserResult.getDatabase(); LOGGER.info(Localization.lang("Automatically setting file links")); AutoSetFileLinksUtil util = new AutoSetFileLinksUtil( parserResult.getDatabaseContext(), preferencesService.getFilePreferences(), preferencesService.getAutoLinkPreferences()); util.linkAssociatedFiles(database.getEntries(), new NamedCompound("")); } } private void regenerateCitationKeys(List<ParserResult> loaded) { for (ParserResult parserResult : loaded) { BibDatabase database = parserResult.getDatabase(); LOGGER.info(Localization.lang("Regenerating citation keys according to metadata")); CitationKeyGenerator keyGenerator = new CitationKeyGenerator( parserResult.getDatabaseContext(), preferencesService.getCitationKeyPatternPreferences()); for (BibEntry entry : database.getEntries()) { keyGenerator.generateAndSetKey(entry); } } } /** * Run an entry fetcher from the command line. * * @param fetchCommand A string containing both the name of the fetcher to use and the search query, separated by a : * @return A parser result containing the entries fetched or null if an error occurred. */ private Optional<ParserResult> fetch(String fetchCommand) { if ((fetchCommand == null) || !fetchCommand.contains(":")) { System.out.println(Localization.lang("Expected syntax for --fetch='<name of fetcher>:<query>'")); System.out.println(Localization.lang("The following fetchers are available:")); return Optional.empty(); } String[] split = fetchCommand.split(":"); String engine = split[0]; String query = split[1]; Set<SearchBasedFetcher> fetchers = WebFetchers.getSearchBasedFetchers( preferencesService.getImportFormatPreferences(), preferencesService.getImporterPreferences()); Optional<SearchBasedFetcher> selectedFetcher = fetchers.stream() .filter(fetcher -> fetcher.getName().equalsIgnoreCase(engine)) .findFirst(); if (selectedFetcher.isEmpty()) { System.out.println(Localization.lang("Could not find fetcher '%0'", engine)); System.out.println(Localization.lang("The following fetchers are available:")); fetchers.forEach(fetcher -> System.out.println(" " + fetcher.getName())); return Optional.empty(); } else { System.out.println(Localization.lang("Running query '%0' with fetcher '%1'.", query, engine)); System.out.print(Localization.lang("Please wait...")); try { List<BibEntry> matches = selectedFetcher.get().performSearch(query); if (matches.isEmpty()) { System.out.println("\r" + Localization.lang("No results found.")); return Optional.empty(); } else { System.out.println("\r" + Localization.lang("Found %0 results.", String.valueOf(matches.size()))); return Optional.of(new ParserResult(matches)); } } catch (FetcherException e) { LOGGER.error("Error while fetching", e); return Optional.empty(); } } } public boolean isBlank() { return cli.isBlank(); } public boolean shouldShutDown() { return cli.isDisableGui() || cli.isShowVersion() || noGUINeeded; } public enum Mode { INITIAL_START, REMOTE_START } }
35,760
43.925879
192
java
null
jabref-main/src/main/java/org/jabref/cli/AuxCommandLine.java
package org.jabref.cli; import java.nio.file.Path; import org.jabref.gui.auximport.AuxParserResultViewModel; import org.jabref.logic.auxparser.AuxParser; import org.jabref.logic.auxparser.AuxParserResult; import org.jabref.logic.auxparser.DefaultAuxParser; import org.jabref.model.database.BibDatabase; import org.jabref.model.strings.StringUtil; public class AuxCommandLine { private final String auxFile; private final BibDatabase database; public AuxCommandLine(String auxFile, BibDatabase database) { this.auxFile = StringUtil.getCorrectFileName(auxFile, "aux"); this.database = database; } public BibDatabase perform() { BibDatabase subDatabase = null; if (!auxFile.isEmpty() && (database != null)) { AuxParser auxParser = new DefaultAuxParser(database); AuxParserResult result = auxParser.parse(Path.of(auxFile)); subDatabase = result.getGeneratedBibDatabase(); // print statistics System.out.println(new AuxParserResultViewModel(result).getInformation(true)); } return subDatabase; } }
1,131
32.294118
90
java
null
jabref-main/src/main/java/org/jabref/cli/JabRefCLI.java
package org.jabref.cli; import java.util.List; import java.util.Objects; import javafx.util.Pair; import org.jabref.gui.Globals; import org.jabref.logic.exporter.ExporterFactory; import org.jabref.logic.importer.ImportFormatReader; import org.jabref.logic.l10n.Localization; import org.jabref.logic.util.OS; import org.jabref.model.strings.StringUtil; import org.jabref.model.util.DummyFileUpdateMonitor; import org.jabref.preferences.PreferencesService; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; public class JabRefCLI { private static final int WIDTH = 100; // Number of characters per line before a line break must be added. private static final String WRAPPED_LINE_PREFIX = ""; // If a line break is added, this prefix will be inserted at the beginning of the next line private static final String STRING_TABLE_DELIMITER = " : "; private final CommandLine cl; private final List<String> leftOver; public JabRefCLI(String[] args) throws ParseException { Options options = getOptions(); this.cl = new DefaultParser().parse(options, args, true); this.leftOver = cl.getArgList(); } public static String getExportMatchesSyntax() { return String.format("[%s]searchTerm,outputFile:%s[,%s]", Localization.lang("field"), Localization.lang("file"), Localization.lang("exportFormat")); } public boolean isHelp() { return cl.hasOption("help"); } public boolean isShowVersion() { return cl.hasOption("version"); } public boolean isBlank() { return cl.hasOption("blank"); } public boolean isDisableGui() { return cl.hasOption("nogui"); } public boolean isPreferencesExport() { return cl.hasOption("prexp"); } public String getPreferencesExport() { return cl.getOptionValue("prexp", "jabref_prefs.xml"); } public boolean isPreferencesImport() { return cl.hasOption("primp"); } public String getPreferencesImport() { return cl.getOptionValue("primp", "jabref_prefs.xml"); } public boolean isPreferencesReset() { return cl.hasOption("prdef"); } public String getPreferencesReset() { return cl.getOptionValue("prdef"); } public boolean isFileExport() { return cl.hasOption("output"); } public String getFileExport() { return cl.getOptionValue("output"); } public boolean isBibtexImport() { return cl.hasOption("importBibtex"); } public String getBibtexImport() { return cl.getOptionValue("importBibtex"); } public boolean isFileImport() { return cl.hasOption("import"); } public String getFileImport() { return cl.getOptionValue("import"); } public boolean isAuxImport() { return cl.hasOption("aux"); } public String getAuxImport() { return cl.getOptionValue("aux"); } public boolean isImportToOpenBase() { return cl.hasOption("importToOpen"); } public String getImportToOpenBase() { return cl.getOptionValue("importToOpen"); } public boolean isDebugLogging() { return cl.hasOption("debug"); } public boolean isFetcherEngine() { return cl.hasOption("fetch"); } public String getFetcherEngine() { return cl.getOptionValue("fetch"); } public boolean isExportMatches() { return cl.hasOption("exportMatches"); } public String getExportMatches() { return cl.getOptionValue("exportMatches"); } public boolean isGenerateCitationKeys() { return cl.hasOption("generateCitationKeys"); } public boolean isAutomaticallySetFileLinks() { return cl.hasOption("automaticallySetFileLinks"); } public boolean isWriteXMPtoPdf() { return cl.hasOption("writeXMPtoPdf"); } public boolean isEmbeddBibfileInPdf() { return cl.hasOption("embeddBibfileInPdf"); } public boolean isWriteMetadatatoPdf() { return cl.hasOption("writeMetadatatoPdf"); } public String getWriteMetadatatoPdf() { return cl.hasOption("writeMetadatatoPdf") ? cl.getOptionValue("writeMetadatatoPdf") : cl.hasOption("writeXMPtoPdf") ? cl.getOptionValue("writeXMPtoPdf") : cl.hasOption("embeddBibfileInPdf") ? cl.getOptionValue("embeddBibfileInPdf") : null; } private static Options getOptions() { Options options = new Options(); // boolean options options.addOption("h", "help", false, Localization.lang("Display help on command line options")); options.addOption("n", "nogui", false, Localization.lang("No GUI. Only process command line options")); options.addOption("asfl", "automaticallySetFileLinks", false, Localization.lang("Automatically set file links")); options.addOption("g", "generateCitationKeys", false, Localization.lang("Regenerate all keys for the entries in a BibTeX file")); options.addOption("b", "blank", false, Localization.lang("Do not open any files at startup")); options.addOption("v", "version", false, Localization.lang("Display version")); options.addOption(null, "debug", false, Localization.lang("Show debug level messages")); // The "-console" option is handled by the install4j launcher options.addOption(null, "console", false, Localization.lang("Show console output (only when the launcher is used)")); options.addOption(Option .builder("i") .longOpt("import") .desc(String.format("%s: '%s'", Localization.lang("Import file"), "-i library.bib")) .hasArg() .argName("FILE[,FORMAT]") .build()); options.addOption(Option .builder() .longOpt("importToOpen") .desc(Localization.lang("Same as --import, but will be imported to the opened tab")) .hasArg() .argName("FILE[,FORMAT]") .build()); options.addOption(Option .builder("ib") .longOpt("importBibtex") .desc(String.format("%s: '%s'", Localization.lang("Import BibTeX"), "-ib @article{entry}")) .hasArg() .argName("BIBTEXT_STRING") .build()); options.addOption(Option .builder("o") .longOpt("output") .desc(String.format("%s: '%s'", Localization.lang("Export an input to a file"), "-i db.bib -o db.htm,html")) .hasArg() .argName("FILE[,FORMAT]") .build()); options.addOption(Option .builder("m") .longOpt("exportMatches") .desc(String.format("%s: '%s'", Localization.lang("Matching"), "-i db.bib -m author=Newton,search.htm,html")) .hasArg() .argName("QUERY,FILE[,FORMAT]") .build()); options.addOption(Option .builder("f") .longOpt("fetch") .desc(String.format("%s: '%s'", Localization.lang("Run fetcher"), "-f Medline/PubMed:cancer")) .hasArg() .argName("FETCHER:QUERY") .build()); options.addOption(Option .builder("a") .longOpt("aux") .desc(String.format("%s: '%s'", Localization.lang("Sublibrary from AUX to BibTeX"), "-a thesis.aux,new.bib")) .hasArg() .argName("FILE[.aux],FILE[.bib] FILE") .build()); options.addOption(Option .builder("x") .longOpt("prexp") .desc(String.format("%s: '%s'", Localization.lang("Export preferences to a file"), "-x prefs.xml")) .hasArg() .argName("[FILE]") .build()); options.addOption(Option .builder("p") .longOpt("primp") .desc(String.format("%s: '%s'", Localization.lang("Import preferences from a file"), "-p prefs.xml")) .hasArg() .argName("[FILE]") .build()); options.addOption(Option .builder("d") .longOpt("prdef") .desc(String.format("%s: '%s'", Localization.lang("Reset preferences"), "-d mainFontSize,newline' or '-d all")) .hasArg() .argName("KEY1[,KEY2][,KEYn] | all") .build()); options.addOption(Option .builder() .longOpt("writeXMPtoPdf") .desc(String.format("%s: '%s'", Localization.lang("Write BibTeXEntry as XMP metadata to PDF."), "-w pathToMyOwnPaper.pdf")) .hasArg() .argName("CITEKEY1[,CITEKEY2][,CITEKEYn] | PDF1[,PDF2][,PDFn] | all") .build()); options.addOption(Option .builder() .longOpt("embeddBibfileInPdf") .desc(String.format("%s: '%s'", Localization.lang("Embed BibTeXEntry in PDF."), "-w pathToMyOwnPaper.pdf")) .hasArg() .argName("CITEKEY1[,CITEKEY2][,CITEKEYn] | PDF1[,PDF2][,PDFn] | all") .build()); options.addOption(Option .builder("w") .longOpt("writeMetadatatoPdf") .desc(String.format("%s: '%s'", Localization.lang("Write BibTeXEntry as metadata to PDF."), "-w pathToMyOwnPaper.pdf")) .hasArg() .argName("CITEKEY1[,CITEKEY2][,CITEKEYn] | PDF1[,PDF2][,PDFn] | all") .build()); return options; } public void displayVersion() { System.out.println(getVersionInfo()); } public static void printUsage(PreferencesService preferencesService) { String header = ""; ImportFormatReader importFormatReader = new ImportFormatReader( preferencesService.getImporterPreferences(), preferencesService.getImportFormatPreferences(), new DummyFileUpdateMonitor()); List<Pair<String, String>> importFormats = importFormatReader .getImportFormats().stream() .map(format -> new Pair<>(format.getName(), format.getId())) .toList(); String importFormatsIntro = Localization.lang("Available import formats"); String importFormatsList = String.format("%s:%n%s%n", importFormatsIntro, alignStringTable(importFormats)); ExporterFactory exporterFactory = ExporterFactory.create( preferencesService, Globals.entryTypesManager); List<Pair<String, String>> exportFormats = exporterFactory .getExporters().stream() .map(format -> new Pair<>(format.getName(), format.getId())) .toList(); String outFormatsIntro = Localization.lang("Available export formats"); String outFormatsList = String.format("%s:%n%s%n", outFormatsIntro, alignStringTable(exportFormats)); String footer = '\n' + importFormatsList + outFormatsList + "\nPlease report issues at https://github.com/JabRef/jabref/issues."; HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(WIDTH, "jabref [OPTIONS] [BIBTEX_FILE]\n\nOptions:", header, getOptions(), footer, true); } private String getVersionInfo() { return String.format("JabRef %s", Globals.BUILD_INFO.version); } public List<String> getLeftOver() { return leftOver; } protected static String alignStringTable(List<Pair<String, String>> table) { StringBuilder sb = new StringBuilder(); int maxLength = table.stream() .mapToInt(pair -> Objects.requireNonNullElse(pair.getKey(), "").length()) .max().orElse(0); for (Pair<String, String> pair : table) { int padding = Math.max(0, maxLength - pair.getKey().length()); sb.append(WRAPPED_LINE_PREFIX); sb.append(pair.getKey()); sb.append(StringUtil.repeatSpaces(padding)); sb.append(STRING_TABLE_DELIMITER); sb.append(pair.getValue()); sb.append(OS.NEWLINE); } return sb.toString(); } /** * Creates and wraps a multi-line and colon-seperated string from a List of Strings. */ protected static String wrapStringList(List<String> list, int firstLineIndentation) { StringBuilder builder = new StringBuilder(); int lastBreak = -firstLineIndentation; for (String line : list) { if (((builder.length() + 2 + line.length()) - lastBreak) > WIDTH) { builder.append(",\n"); lastBreak = builder.length(); builder.append(WRAPPED_LINE_PREFIX); } else if (builder.length() > 0) { builder.append(", "); } builder.append(line); } return builder.toString(); } }
13,472
34.548813
149
java
null
jabref-main/src/main/java/org/jabref/cli/Launcher.java
package org.jabref.cli; import java.io.File; import java.io.IOException; import java.net.Authenticator; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.Comparator; import java.util.Map; import org.jabref.gui.Globals; import org.jabref.gui.MainApplication; import org.jabref.logic.journals.JournalAbbreviationLoader; import org.jabref.logic.l10n.Localization; import org.jabref.logic.net.ProxyAuthenticator; import org.jabref.logic.net.ProxyPreferences; import org.jabref.logic.net.ProxyRegisterer; import org.jabref.logic.net.ssl.SSLPreferences; import org.jabref.logic.net.ssl.TrustStoreManager; import org.jabref.logic.protectedterms.ProtectedTermsLoader; import org.jabref.logic.remote.RemotePreferences; import org.jabref.logic.remote.client.RemoteClient; import org.jabref.logic.util.OS; import org.jabref.migrations.PreferencesMigrations; import org.jabref.model.util.FileUpdateMonitor; import org.jabref.preferences.JabRefPreferences; import org.jabref.preferences.PreferencesService; import org.apache.commons.cli.ParseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.tinylog.configuration.Configuration; /** * The main entry point for the JabRef application. * <p> * It has two main functions: * - Handle the command line arguments * - Start the JavaFX application (if not in cli mode) */ public class Launcher { private static Logger LOGGER; private static String[] ARGUMENTS; public static void main(String[] args) { ARGUMENTS = args; addLogToDisk(); try { // Init preferences final JabRefPreferences preferences = JabRefPreferences.getInstance(); Globals.prefs = preferences; PreferencesMigrations.runMigrations(preferences); // Early exit in case another instance is already running if (!handleMultipleAppInstances(ARGUMENTS, preferences)) { return; } // Init rest of preferences configureProxy(preferences.getProxyPreferences()); configureSSL(preferences.getSSLPreferences()); initGlobals(preferences); clearOldSearchIndices(); try { FileUpdateMonitor fileUpdateMonitor = Globals.getFileUpdateMonitor(); // Process arguments ArgumentProcessor argumentProcessor = new ArgumentProcessor( ARGUMENTS, ArgumentProcessor.Mode.INITIAL_START, preferences, fileUpdateMonitor); if (argumentProcessor.shouldShutDown()) { LOGGER.debug("JabRef shut down after processing command line arguments"); return; } MainApplication.main(argumentProcessor.getParserResults(), argumentProcessor.isBlank(), preferences, fileUpdateMonitor, ARGUMENTS); } catch (ParseException e) { LOGGER.error("Problem parsing arguments", e); JabRefCLI.printUsage(preferences); } } catch (Exception ex) { LOGGER.error("Unexpected exception", ex); } } /** * This needs to be called as early as possible. After the first log write, it * is not possible to alter * the log configuration programmatically anymore. */ private static void addLogToDisk() { Path directory = OS.getNativeDesktop().getLogDirectory(); try { Files.createDirectories(directory); } catch (IOException e) { initializeLogger(); LOGGER.error("Could not create log directory {}", directory, e); return; } // The "Shared File Writer" is explained at // https://tinylog.org/v2/configuration/#shared-file-writer Map<String, String> configuration = Map.of( "writerFile", "shared file", "writerFile.level", "debug", "writerFile.file", directory.resolve("log.txt").toString(), "writerFile.charset", "UTF-8"); configuration.entrySet().forEach(config -> Configuration.set(config.getKey(), config.getValue())); initializeLogger(); } private static void initializeLogger() { LOGGER = LoggerFactory.getLogger(MainApplication.class); } private static boolean handleMultipleAppInstances(String[] args, PreferencesService preferences) { RemotePreferences remotePreferences = preferences.getRemotePreferences(); if (remotePreferences.useRemoteServer()) { // Try to contact already running JabRef RemoteClient remoteClient = new RemoteClient(remotePreferences.getPort()); if (remoteClient.ping()) { // We are not alone, there is already a server out there, send command line // arguments to other instance if (remoteClient.sendCommandLineArguments(args)) { // So we assume it's all taken care of, and quit. LOGGER.info(Localization.lang("Arguments passed on to running JabRef instance. Shutting down.")); return false; } else { LOGGER.warn("Could not communicate with other running JabRef instance."); } } } return true; } private static void initGlobals(PreferencesService preferences) { // Read list(s) of journal names and abbreviations Globals.journalAbbreviationRepository = JournalAbbreviationLoader .loadRepository(preferences.getJournalAbbreviationPreferences()); Globals.entryTypesManager = preferences.getCustomEntryTypesRepository(); Globals.protectedTermsLoader = new ProtectedTermsLoader(preferences.getProtectedTermsPreferences()); } private static void configureProxy(ProxyPreferences proxyPreferences) { ProxyRegisterer.register(proxyPreferences); if (proxyPreferences.shouldUseProxy() && proxyPreferences.shouldUseAuthentication()) { Authenticator.setDefault(new ProxyAuthenticator()); } } private static void configureSSL(SSLPreferences sslPreferences) { TrustStoreManager.createTruststoreFileIfNotExist(Path.of(sslPreferences.getTruststorePath())); System.setProperty("javax.net.ssl.trustStore", sslPreferences.getTruststorePath()); System.setProperty("javax.net.ssl.trustStorePassword", "changeit"); } private static void clearOldSearchIndices() { Path currentIndexPath = OS.getNativeDesktop().getFulltextIndexBaseDirectory(); Path appData = currentIndexPath.getParent(); try { Files.createDirectories(currentIndexPath); } catch (IOException e) { LOGGER.error("Could not create index directory {}", appData, e); } try (DirectoryStream<Path> stream = Files.newDirectoryStream(appData)) { for (Path path : stream) { if (Files.isDirectory(path) && !path.toString().endsWith("ssl") && path.toString().contains("lucene") && !path.equals(currentIndexPath)) { LOGGER.info("Deleting out-of-date fulltext search index at {}.", path); Files.walk(path) .sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(File::delete); } } } catch (IOException e) { LOGGER.error("Could not access app-directory at {}", appData, e); } } }
7,712
40.026596
147
java
null
jabref-main/src/main/java/org/jabref/cli/SystemOutputPrinter.java
package org.jabref.cli; import org.jabref.logic.importer.OutputPrinter; public class SystemOutputPrinter implements OutputPrinter { @Override public void setStatus(String s) { System.out.println(s); } @Override public void showMessage(String message, String title, int msgType) { System.out.println(title + ": " + message); } @Override public void showMessage(String message) { System.out.println(message); } }
476
20.681818
72
java
null
jabref-main/src/main/java/org/jabref/gui/AbstractViewModel.java
package org.jabref.gui; public class AbstractViewModel { // empty }
73
11.333333
32
java
null
jabref-main/src/main/java/org/jabref/gui/BasePanelMode.java
package org.jabref.gui; /** * Defines the different modes that the BasePanel can operate in */ public enum BasePanelMode { SHOWING_NOTHING, SHOWING_EDITOR, WILL_SHOW_EDITOR }
191
15
64
java
null
jabref-main/src/main/java/org/jabref/gui/ClipBoardManager.java
package org.jabref.gui; import java.awt.Toolkit; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.IOException; import java.util.List; import javafx.application.Platform; import javafx.scene.control.TextInputControl; import javafx.scene.input.Clipboard; import javafx.scene.input.ClipboardContent; import javafx.scene.input.DataFormat; import javafx.scene.input.MouseButton; import org.jabref.architecture.AllowedToUseAwt; import org.jabref.logic.bibtex.BibEntryWriter; import org.jabref.logic.bibtex.FieldWriter; import org.jabref.model.database.BibDatabaseMode; import org.jabref.model.entry.BibEntry; import org.jabref.preferences.PreferencesService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @AllowedToUseAwt("Requires ava.awt.datatransfer.Clipboard") public class ClipBoardManager { public static final DataFormat XML = new DataFormat("application/xml"); private static final Logger LOGGER = LoggerFactory.getLogger(ClipBoardManager.class); private static Clipboard clipboard; private static java.awt.datatransfer.Clipboard primary; private final PreferencesService preferencesService; public ClipBoardManager(PreferencesService preferencesService) { this(Clipboard.getSystemClipboard(), Toolkit.getDefaultToolkit().getSystemSelection(), preferencesService); } public ClipBoardManager(Clipboard clipboard, java.awt.datatransfer.Clipboard primary, PreferencesService preferencesService) { ClipBoardManager.clipboard = clipboard; ClipBoardManager.primary = primary; this.preferencesService = preferencesService; } /** * Add X11 clipboard support to a text input control. It is necessary to call this method in every input where you * want to use it: {@code ClipBoardManager.addX11Support(TextInputControl input);}. * * @param input the TextInputControl (e.g., TextField, TextArea, and children) where adding this functionality. * @see <a href="https://www.uninformativ.de/blog/postings/2017-04-02/0/POSTING-en.html">Short summary for X11 * clipboards</a> * @see <a href="https://unix.stackexchange.com/questions/139191/whats-the-difference-between-primary-selection-and-clipboard-buffer/139193#139193">Longer * text over clipboards</a> */ public static void addX11Support(TextInputControl input) { input.selectedTextProperty().addListener( // using InvalidationListener because of https://bugs.openjdk.java.net/browse/JDK-8176270 observable -> Platform.runLater(() -> { String newValue = input.getSelectedText(); if (!newValue.isEmpty() && (primary != null)) { primary.setContents(new StringSelection(newValue), null); } })); input.setOnMouseClicked(event -> { if (event.getButton() == MouseButton.MIDDLE) { input.insertText(input.getCaretPosition(), getContentsPrimary()); } }); } /** * Get the String residing on the system clipboard. * * @return any text found on the Clipboard; if none found, return an empty String. */ public static String getContents() { String result = clipboard.getString(); if (result == null) { return ""; } return result; } /** * Get the String residing on the primary clipboard (if it exists). * * @return any text found on the primary Clipboard; if none found, try with the system clipboard. */ public static String getContentsPrimary() { if (primary != null) { Transferable contents = primary.getContents(null); if ((contents != null) && contents.isDataFlavorSupported(DataFlavor.stringFlavor)) { try { return (String) contents.getTransferData(DataFlavor.stringFlavor); } catch (UnsupportedFlavorException | IOException e) { LOGGER.warn(e.getMessage()); } } } return getContents(); } /** * Puts content onto the system clipboard. * * @param content the ClipboardContent to set as current value of the system clipboard. */ public void setContent(ClipboardContent content) { clipboard.setContent(content); setPrimaryClipboardContent(content); } /** * Puts content onto the primary clipboard (if it exists). * * @param content the ClipboardContent to set as current value of the primary clipboard. */ public void setPrimaryClipboardContent(ClipboardContent content) { if (primary != null) { primary.setContents(new StringSelection(content.getString()), null); } } public void setHtmlContent(String html, String fallbackPlain) { final ClipboardContent content = new ClipboardContent(); content.putHtml(html); content.putString(fallbackPlain); clipboard.setContent(content); setPrimaryClipboardContent(content); } public void setContent(String string) { final ClipboardContent content = new ClipboardContent(); content.putString(string); clipboard.setContent(content); setPrimaryClipboardContent(content); } public void setContent(List<BibEntry> entries) throws IOException { final ClipboardContent content = new ClipboardContent(); BibEntryWriter writer = new BibEntryWriter(new FieldWriter(preferencesService.getFieldPreferences()), Globals.entryTypesManager); String serializedEntries = writer.serializeAll(entries, BibDatabaseMode.BIBTEX); // BibEntry is not Java serializable. Thus, we need to do the serialization manually // At reading of the clipboard in JabRef, we parse the plain string in all cases, so we don't need to flag we put BibEntries here // Furthermore, storing a string also enables other applications to work with the data content.putString(serializedEntries); clipboard.setContent(content); setPrimaryClipboardContent(content); } }
6,324
39.544872
158
java
null
jabref-main/src/main/java/org/jabref/gui/DefaultInjector.java
package org.jabref.gui; import java.util.function.Function; import javax.swing.undo.UndoManager; import org.jabref.gui.keyboard.KeyBindingRepository; import org.jabref.gui.theme.ThemeManager; import org.jabref.gui.util.TaskExecutor; import org.jabref.logic.journals.JournalAbbreviationRepository; import org.jabref.logic.protectedterms.ProtectedTermsLoader; import org.jabref.model.entry.BibEntryTypesManager; import org.jabref.model.util.FileUpdateMonitor; import org.jabref.preferences.PreferencesService; import com.airhacks.afterburner.injection.Injector; import com.airhacks.afterburner.injection.PresenterFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DefaultInjector implements PresenterFactory { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultInjector.class); /** * This method takes care of creating dependencies. * By default, it just creates a new instance of the class. * Dependencies without default constructor are constructed by hand. */ private static Object createDependency(Class<?> clazz) { if (clazz == DialogService.class) { return JabRefGUI.getMainFrame().getDialogService(); } else if (clazz == TaskExecutor.class) { return Globals.TASK_EXECUTOR; } else if (clazz == PreferencesService.class) { return Globals.prefs; } else if (clazz == KeyBindingRepository.class) { return Globals.getKeyPrefs(); } else if (clazz == JournalAbbreviationRepository.class) { return Globals.journalAbbreviationRepository; } else if (clazz == StateManager.class) { return Globals.stateManager; } else if (clazz == ThemeManager.class) { return Globals.getThemeManager(); } else if (clazz == FileUpdateMonitor.class) { return Globals.getFileUpdateMonitor(); } else if (clazz == ProtectedTermsLoader.class) { return Globals.protectedTermsLoader; } else if (clazz == ClipBoardManager.class) { return Globals.getClipboardManager(); } else if (clazz == UndoManager.class) { return Globals.undoManager; } else if (clazz == BibEntryTypesManager.class) { return Globals.entryTypesManager; } else { try { return clazz.newInstance(); } catch (InstantiationException | IllegalAccessException ex) { LOGGER.error("Cannot instantiate dependency: " + clazz, ex); return null; } } } @Override public <T> T instantiatePresenter(Class<T> clazz, Function<String, Object> injectionContext) { LOGGER.debug("Instantiate {}", clazz.getName()); // Use our own method to construct dependencies Injector.setInstanceSupplier(DefaultInjector::createDependency); return Injector.instantiatePresenter(clazz, injectionContext); } @Override public void injectMembers(Object instance, Function<String, Object> injectionContext) { LOGGER.debug("Inject into {}", instance.getClass().getName()); // Use our own method to construct dependencies Injector.setInstanceSupplier(DefaultInjector::createDependency); Injector.injectMembers(instance, injectionContext); } }
3,360
38.541176
98
java
null
jabref-main/src/main/java/org/jabref/gui/Dialog.java
package org.jabref.gui; import java.util.Optional; public interface Dialog<R> { Optional<R> showAndWait(); }
115
13.5
30
java
null
jabref-main/src/main/java/org/jabref/gui/DialogService.java
package org.jabref.gui; import java.io.IOException; import java.nio.file.Path; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.function.Consumer; import javafx.concurrent.Task; import javafx.print.PrinterJob; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.scene.control.ChoiceDialog; import javafx.scene.control.DialogPane; import javafx.scene.control.TextInputDialog; import org.jabref.gui.util.BaseDialog; import org.jabref.gui.util.DirectoryDialogConfiguration; import org.jabref.gui.util.FileDialogConfiguration; import org.jabref.logic.l10n.Localization; import org.controlsfx.control.textfield.CustomPasswordField; import org.controlsfx.dialog.ProgressDialog; /** * This interface provides methods to create dialogs and show them to the user. */ public interface DialogService { /** * This will create and display new {@link ChoiceDialog} of type T with a default choice and a collection of possible choices * * @implNote The implementation should accept {@code null} for {@code defaultChoice}, but callers should use {@link #showChoiceDialogAndWait(String, String, String, Collection)}. */ <T> Optional<T> showChoiceDialogAndWait(String title, String content, String okButtonLabel, T defaultChoice, Collection<T> choices); /** * This will create and display new {@link ChoiceDialog} of type T with a collection of possible choices */ default <T> Optional<T> showChoiceDialogAndWait(String title, String content, String okButtonLabel, Collection<T> choices) { return showChoiceDialogAndWait(title, content, okButtonLabel, null, choices); } /** * This will create and display new {@link TextInputDialog} with a text fields to enter data */ Optional<String> showInputDialogAndWait(String title, String content); /** * This will create and display new {@link TextInputDialog} with a text field with a default value to enter data */ Optional<String> showInputDialogWithDefaultAndWait(String title, String content, String defaultValue); /** * This will create and display a new information dialog. * It will include a blue information icon on the left and * a single OK Button. To create an information dialog with custom * buttons see also {@link #showCustomButtonDialogAndWait(Alert.AlertType, String, String, ButtonType...)} */ void showInformationDialogAndWait(String title, String content); /** * This will create and display a new information dialog. * It will include a yellow warning icon on the left and * a single OK Button. To create a warning dialog with custom * buttons see also {@link #showCustomButtonDialogAndWait(Alert.AlertType, String, String, ButtonType...)} */ void showWarningDialogAndWait(String title, String content); /** * This will create and display a new error dialog. * It will include a red error icon on the left and * a single OK Button. To create a error dialog with custom * buttons see also {@link #showCustomButtonDialogAndWait(Alert.AlertType, String, String, ButtonType...)} */ void showErrorDialogAndWait(String title, String content); /** * Create and display error dialog displaying the given exception. * * @param message the error message * @param exception the exception causing the error */ void showErrorDialogAndWait(String message, Throwable exception); /** * Create and display error dialog displaying the given exception. * * @param exception the exception causing the error */ default void showErrorDialogAndWait(Exception exception) { showErrorDialogAndWait(Localization.lang("Unhandled exception occurred."), exception); } /** * Create and display error dialog displaying the given exception. * * @param exception the exception causing the error */ void showErrorDialogAndWait(String title, String content, Throwable exception); /** * Create and display error dialog displaying the given message. * * @param message the error message */ void showErrorDialogAndWait(String message); /** * This will create and display a new confirmation dialog. * It will include a blue question icon on the left and * a OK and Cancel button. To create a confirmation dialog with custom * buttons see also {@link #showCustomButtonDialogAndWait(Alert.AlertType, String, String, ButtonType...)} * * @return true if the use clicked "OK" otherwise false */ boolean showConfirmationDialogAndWait(String title, String content); /** * Create and display a new confirmation dialog. * It will include a blue question icon on the left and * a OK (with given label) and Cancel button. To create a confirmation dialog with custom * buttons see also {@link #showCustomButtonDialogAndWait(Alert.AlertType, String, String, ButtonType...)}. * * @return true if the use clicked "OK" otherwise false */ boolean showConfirmationDialogAndWait(String title, String content, String okButtonLabel); /** * Create and display a new confirmation dialog. * It will include a blue question icon on the left and * a OK (with given label) and Cancel (also with given label) button. To create a confirmation dialog with custom * buttons see also {@link #showCustomButtonDialogAndWait(Alert.AlertType, String, String, ButtonType...)}. * * @return true if the use clicked "OK" otherwise false */ boolean showConfirmationDialogAndWait(String title, String content, String okButtonLabel, String cancelButtonLabel); /** * Create and display a new confirmation dialog. * It will include a blue question icon on the left and * a YES (with given label) and Cancel (also with given label) button. To create a confirmation dialog with custom * buttons see also {@link #showCustomButtonDialogAndWait(Alert.AlertType, String, String, ButtonType...)}. * Moreover, the dialog contains a opt-out checkbox with the given text to support "Do not ask again"-behaviour. * * @return true if the use clicked "YES" otherwise false */ boolean showConfirmationDialogWithOptOutAndWait(String title, String content, String optOutMessage, Consumer<Boolean> optOutAction); /** * Create and display a new confirmation dialog. * It will include a blue question icon on the left and * a YES (with given label) and Cancel (also with given label) button. To create a confirmation dialog with custom * buttons see also {@link #showCustomButtonDialogAndWait(Alert.AlertType, String, String, ButtonType...)}. * Moreover, the dialog contains a opt-out checkbox with the given text to support "Do not ask again"-behaviour. * * @return true if the use clicked "YES" otherwise false */ boolean showConfirmationDialogWithOptOutAndWait(String title, String content, String okButtonLabel, String cancelButtonLabel, String optOutMessage, Consumer<Boolean> optOutAction); /** * This will create and display new {@link CustomPasswordField} that doesn't show the text, and two buttons * one cancel and one ok. * * @return the entered password if pressed "OK", null otherwise */ Optional<String> showPasswordDialogAndWait(String title, String header, String content); /** * Shows a custom dialog without returning any results. * * @param dialog dialog to show */ void showCustomDialog(BaseDialog<?> dialog); /** * This will create and display a new dialog of the specified * {@link Alert.AlertType} but with user defined buttons as optional * {@link ButtonType}s. * * @return Optional with the pressed Button as ButtonType */ Optional<ButtonType> showCustomButtonDialogAndWait(Alert.AlertType type, String title, String content, ButtonType... buttonTypes); /** * This will create and display a new dialog showing a custom {@link DialogPane} * and using custom {@link ButtonType}s. * * @return Optional with the pressed Button as ButtonType */ Optional<ButtonType> showCustomDialogAndWait(String title, DialogPane contentPane, ButtonType... buttonTypes); /** * Shows a custom dialog and returns the result. * * @param dialog dialog to show * @param <R> type of result */ <R> Optional<R> showCustomDialogAndWait(javafx.scene.control.Dialog<R> dialog); /** * Constructs and shows a canceable {@link ProgressDialog}. Clicking cancel will cancel the underlying service and close the dialog * * @param title title of the dialog * @param content message to show above the progress bar * @param task The {@link Task} which executes the work and for which to show the dialog */ <V> void showProgressDialog(String title, String content, Task<V> task); /** * Constructs and shows a dialog showing the progress of running background tasks. * Clicking cancel will cancel the underlying service and close the dialog. * The dialog will exit as soon as none of the background tasks are running * * @param title title of the dialog * @param content message to show below the list of background tasks * @param stateManager The {@link StateManager} which contains the background tasks */ <V> Optional<ButtonType> showBackgroundProgressDialogAndWait(String title, String content, StateManager stateManager); /** * Notify the user in a non-blocking way (i.e., in form of toast in a snackbar). * * @param message the message to show. */ void notify(String message); /** * Shows a new file save dialog. The method doesn't return until the * displayed file save dialog is dismissed. The return value specifies the * file chosen by the user or an empty {@link Optional} if no selection has been made. * After a file was selected, the given file dialog configuration is updated with the selected extension type (if any). * * @return the selected file or an empty {@link Optional} if no file has been selected */ Optional<Path> showFileSaveDialog(FileDialogConfiguration fileDialogConfiguration); /** * Shows a new file open dialog. The method doesn't return until the * displayed open dialog is dismissed. The return value specifies * the file chosen by the user or an empty {@link Optional} if no selection has been * made. * After a file was selected, the given file dialog configuration is updated with the selected extension type (if any). * * @return the selected file or an empty {@link Optional} if no file has been selected */ Optional<Path> showFileOpenDialog(FileDialogConfiguration fileDialogConfiguration); /** * Shows a new file open dialog. The method doesn't return until the * displayed open dialog is dismissed. The return value specifies * the files chosen by the user or an empty {@link List} if no selection has been * made. * * @return the selected files or an empty {@link List} if no file has been selected */ List<Path> showFileOpenDialogAndGetMultipleFiles(FileDialogConfiguration fileDialogConfiguration); /** * Shows a new directory selection dialog. The method doesn't return until the * displayed open dialog is dismissed. The return value specifies * the file chosen by the user or an empty {@link Optional} if no selection has been * made. * * @return the selected directory or an empty {@link Optional} if no directory has been selected */ Optional<Path> showDirectorySelectionDialog(DirectoryDialogConfiguration directoryDialogConfiguration); /** * Displays a Print Dialog. Allow the user to update job state such as printer and settings. These changes will be * available in the appropriate properties after the print dialog has returned. The print dialog is also used to * confirm the user wants to proceed with printing. * * @param job the print job to customize * @return false if the user opts to cancel printing */ boolean showPrintDialog(PrinterJob job); /** * Shows a new dialog that list all files contained in the given archive and which lets the user select one of these * files. The method doesn't return until the displayed open dialog is dismissed. The return value specifies the * file chosen by the user or an empty {@link Optional} if no selection has been made. * * @return the selected file or an empty {@link Optional} if no file has been selected */ Optional<Path> showFileOpenFromArchiveDialog(Path archivePath) throws IOException; }
13,166
43.938567
182
java
null
jabref-main/src/main/java/org/jabref/gui/DragAndDropDataFormats.java
package org.jabref.gui; import java.util.List; import javafx.scene.input.DataFormat; import org.jabref.logic.preview.PreviewLayout; /** * Contains all the different {@link DataFormat}s that may occur in JabRef. */ public class DragAndDropDataFormats { public static final DataFormat FIELD = new DataFormat("dnd/org.jabref.model.entry.field.Field"); public static final DataFormat GROUP = new DataFormat("dnd/org.jabref.model.groups.GroupTreeNode"); public static final DataFormat LINKED_FILE = new DataFormat("dnd/org.jabref.model.entry.LinkedFile"); public static final DataFormat ENTRIES = new DataFormat("dnd/org.jabref.model.entry.BibEntries"); public static final DataFormat PREVIEWLAYOUTS = new DataFormat("dnd/org.jabref.logic.citationstyle.PreviewLayouts"); @SuppressWarnings("unchecked") public static final Class<List<PreviewLayout>> PREVIEWLAYOUT_LIST_CLASS = (Class<List<PreviewLayout>>) (Class<?>) List.class; }
956
44.571429
160
java
null
jabref-main/src/main/java/org/jabref/gui/DragAndDropHelper.java
package org.jabref.gui; import java.io.File; import java.nio.file.Path; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import javafx.scene.input.Dragboard; import org.jabref.logic.util.io.FileUtil; public class DragAndDropHelper { public static boolean hasBibFiles(Dragboard dragboard) { return !getBibFiles(dragboard).isEmpty(); } public static List<Path> getBibFiles(Dragboard dragboard) { if (!dragboard.hasFiles()) { return Collections.emptyList(); } else { return dragboard.getFiles().stream().map(File::toPath).filter(FileUtil::isBibFile).collect(Collectors.toList()); } } public static boolean hasGroups(Dragboard dragboard) { return !getGroups(dragboard).isEmpty(); } public static List<String> getGroups(Dragboard dragboard) { if (!dragboard.hasContent(DragAndDropDataFormats.GROUP)) { return Collections.emptyList(); } else { return (List<String>) dragboard.getContent(DragAndDropDataFormats.GROUP); } } }
1,110
27.487179
124
java
null
jabref-main/src/main/java/org/jabref/gui/EntryTypeView.java
package org.jabref.gui; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import javafx.application.Platform; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.ComboBox; import javafx.scene.control.TextField; import javafx.scene.control.TitledPane; import javafx.scene.control.Tooltip; import javafx.scene.layout.FlowPane; import javafx.stage.Screen; import org.jabref.gui.util.BaseDialog; import org.jabref.gui.util.ControlHelper; import org.jabref.gui.util.IconValidationDecorator; import org.jabref.gui.util.TaskExecutor; import org.jabref.gui.util.ViewModelListCellFactory; import org.jabref.logic.importer.IdBasedFetcher; import org.jabref.logic.importer.WebFetcher; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseMode; import org.jabref.model.entry.BibEntryType; import org.jabref.model.entry.types.BiblatexAPAEntryTypeDefinitions; import org.jabref.model.entry.types.BiblatexEntryTypeDefinitions; import org.jabref.model.entry.types.BiblatexSoftwareEntryTypeDefinitions; import org.jabref.model.entry.types.BibtexEntryTypeDefinitions; import org.jabref.model.entry.types.EntryType; import org.jabref.model.entry.types.IEEETranEntryTypeDefinitions; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.model.strings.StringUtil; import org.jabref.model.util.FileUpdateMonitor; import org.jabref.preferences.PreferencesService; import com.airhacks.afterburner.views.ViewLoader; import com.tobiasdiez.easybind.EasyBind; import de.saxsys.mvvmfx.utils.validation.visualization.ControlsFxVisualizer; import jakarta.inject.Inject; /** * Dialog that prompts the user to choose a type for an entry. */ public class EntryTypeView extends BaseDialog<EntryType> { @Inject private StateManager stateManager; @Inject private TaskExecutor taskExecutor; @Inject private FileUpdateMonitor fileUpdateMonitor; @FXML private ButtonType generateButton; @FXML private TextField idTextField; @FXML private ComboBox<IdBasedFetcher> idBasedFetchers; @FXML private FlowPane recommendedEntriesPane; @FXML private FlowPane otherEntriesPane; @FXML private FlowPane customPane; @FXML private TitledPane recommendedEntriesTitlePane; @FXML private TitledPane otherEntriesTitlePane; @FXML private TitledPane customTitlePane; private final LibraryTab libraryTab; private final DialogService dialogService; private final PreferencesService preferencesService; private EntryType type; private EntryTypeViewModel viewModel; private final ControlsFxVisualizer visualizer = new ControlsFxVisualizer(); public EntryTypeView(LibraryTab libraryTab, DialogService dialogService, PreferencesService preferences) { this.libraryTab = libraryTab; this.dialogService = dialogService; this.preferencesService = preferences; this.setTitle(Localization.lang("Select entry type")); ViewLoader.view(this) .load() .setAsDialogPane(this); ControlHelper.setAction(generateButton, this.getDialogPane(), event -> viewModel.runFetcherWorker()); setResultConverter(button -> { // The buttonType will always be "cancel", even if we pressed one of the entry type buttons return type; }); Button btnGenerate = (Button) this.getDialogPane().lookupButton(generateButton); btnGenerate.textProperty().bind(EasyBind.map(viewModel.searchingProperty(), searching -> searching ? Localization.lang("Searching...") : Localization.lang("Generate"))); btnGenerate.disableProperty().bind(viewModel.idFieldValidationStatus().validProperty().not().or(viewModel.searchingProperty())); EasyBind.subscribe(viewModel.searchSuccesfulProperty(), value -> { if (value) { setEntryTypeForReturnAndClose(Optional.empty()); } }); } private void addEntriesToPane(FlowPane pane, Collection<? extends BibEntryType> entries) { for (BibEntryType entryType : entries) { Button entryButton = new Button(entryType.getType().getDisplayName()); entryButton.setUserData(entryType); entryButton.setOnAction(event -> setEntryTypeForReturnAndClose(Optional.of(entryType))); pane.getChildren().add(entryButton); EntryType selectedType = entryType.getType(); String description = getDescription(selectedType); if (StringUtil.isNotBlank(description)) { Screen currentScreen = Screen.getPrimary(); double maxWidth = currentScreen.getBounds().getWidth(); Tooltip tooltip = new Tooltip(description); tooltip.setMaxWidth((maxWidth * 2) / 3); tooltip.setWrapText(true); entryButton.setTooltip(tooltip); } } } @FXML public void initialize() { visualizer.setDecoration(new IconValidationDecorator()); viewModel = new EntryTypeViewModel( preferencesService, libraryTab, dialogService, stateManager, taskExecutor, fileUpdateMonitor); idBasedFetchers.itemsProperty().bind(viewModel.fetcherItemsProperty()); idTextField.textProperty().bindBidirectional(viewModel.idTextProperty()); idBasedFetchers.valueProperty().bindBidirectional(viewModel.selectedItemProperty()); EasyBind.subscribe(viewModel.getFocusAndSelectAllProperty(), evt -> { if (evt) { idTextField.requestFocus(); idTextField.selectAll(); } }); new ViewModelListCellFactory<IdBasedFetcher>().withText(WebFetcher::getName).install(idBasedFetchers); // we set the managed property so that they will only be rendered when they are visble so that the Nodes only take the space when visible // avoids removing and adding from the scence graph recommendedEntriesTitlePane.managedProperty().bind(recommendedEntriesTitlePane.visibleProperty()); otherEntriesTitlePane.managedProperty().bind(otherEntriesTitlePane.visibleProperty()); customTitlePane.managedProperty().bind(customTitlePane.visibleProperty()); otherEntriesTitlePane.expandedProperty().addListener((obs, wasExpanded, isNowExpanded) -> { if (isNowExpanded) { this.setHeight(this.getHeight() + otherEntriesPane.getHeight()); } else { this.setHeight(this.getHeight() - otherEntriesPane.getHeight()); } }); boolean isBiblatexMode = libraryTab.getBibDatabaseContext().isBiblatexMode(); List<BibEntryType> recommendedEntries; List<BibEntryType> otherEntries; if (isBiblatexMode) { recommendedEntries = BiblatexEntryTypeDefinitions.RECOMMENDED; otherEntries = BiblatexEntryTypeDefinitions.ALL .stream() .filter(e -> !recommendedEntries.contains(e)) .collect(Collectors.toList()); otherEntries.addAll(BiblatexSoftwareEntryTypeDefinitions.ALL); otherEntries.addAll(BiblatexAPAEntryTypeDefinitions.ALL); } else { recommendedEntries = BibtexEntryTypeDefinitions.RECOMMENDED; otherEntries = BibtexEntryTypeDefinitions.ALL .stream() .filter(e -> !recommendedEntries.contains(e)) .collect(Collectors.toList()); otherEntries.addAll(IEEETranEntryTypeDefinitions.ALL); } addEntriesToPane(recommendedEntriesPane, recommendedEntries); addEntriesToPane(otherEntriesPane, otherEntries); BibDatabaseMode customTypeDatabaseMode = isBiblatexMode ? BibDatabaseMode.BIBLATEX : BibDatabaseMode.BIBTEX; List<BibEntryType> customTypes = Globals.entryTypesManager.getAllCustomTypes(customTypeDatabaseMode); if (customTypes.isEmpty()) { customTitlePane.setVisible(false); } else { addEntriesToPane(customPane, customTypes); } viewModel.idTextProperty().addListener((obs, oldValue, newValue) -> visualizer.initVisualization(viewModel.idFieldValidationStatus(), idTextField, true)); Platform.runLater(() -> idTextField.requestFocus()); } public EntryType getChoice() { return type; } @FXML private void runFetcherWorker(Event event) { viewModel.runFetcherWorker(); } @FXML private void focusTextField(Event event) { idTextField.requestFocus(); idTextField.selectAll(); } private void setEntryTypeForReturnAndClose(Optional<BibEntryType> entryType) { type = entryType.map(BibEntryType::getType).orElse(null); viewModel.stopFetching(); this.stateManager.clearSearchQuery(); this.close(); } /** * The description is originating from biblatex manual chapter 2 Biblatex documentation is favored over the bibtex, since bibtex is a subset of biblatex and biblatex is better documented. */ public static String getDescription(EntryType selectedType) { if (selectedType instanceof StandardEntryType entryType) { switch (entryType) { case Article -> { return Localization.lang("An article in a journal, magazine, newspaper, or other periodical which forms a self-contained unit with its own title."); } case Book -> { return Localization.lang("A single-volume book with one or more authors where the authors share credit for the work as a whole."); } case Booklet -> { return Localization.lang("A book-like work without a formal publisher or sponsoring institution."); } case Collection -> { return Localization.lang("A single-volume collection with multiple, self-contained contributions by distinct authors which have their own title. The work as a whole has no overall author but it will usually have an editor."); } case Conference -> { return Localization.lang("A legacy alias for \"InProceedings\"."); } case InBook -> { return Localization.lang("A part of a book which forms a self-contained unit with its own title."); } case InCollection -> { return Localization.lang("A contribution to a collection which forms a self-contained unit with a distinct author and title."); } case InProceedings -> { return Localization.lang("An article in a conference proceedings."); } case Manual -> { return Localization.lang("Technical or other documentation, not necessarily in printed form."); } case MastersThesis -> { return Localization.lang("Similar to \"Thesis\" except that the type field is optional and defaults to the localised term Master's thesis."); } case Misc -> { return Localization.lang("A fallback type for entries which do not fit into any other category."); } case PhdThesis -> { return Localization.lang("Similar to \"Thesis\" except that the type field is optional and defaults to the localised term PhD thesis."); } case Proceedings -> { return Localization.lang("A single-volume conference proceedings. This type is very similar to \"Collection\"."); } case TechReport -> { return Localization.lang("Similar to \"Report\" except that the type field is optional and defaults to the localised term technical report."); } case Unpublished -> { return Localization.lang("A work with an author and a title which has not been formally published, such as a manuscript or the script of a talk."); } case BookInBook -> { return Localization.lang("This type is similar to \"InBook\" but intended for works originally published as a stand-alone book."); } case InReference -> { return Localization.lang("An article in a work of reference. This is a more specific variant of the generic \"InCollection\" entry type."); } case MvBook -> { return Localization.lang("A multi-volume \"Book\"."); } case MvCollection -> { return Localization.lang("A multi-volume \"Collection\"."); } case MvProceedings -> { return Localization.lang("A multi-volume \"Proceedings\" entry."); } case MvReference -> { return Localization.lang("A multi-volume \"Reference\" entry. The standard styles will treat this entry type as an alias for \"MvCollection\"."); } case Online -> { return Localization.lang("This entry type is intended for sources such as web sites which are intrinsically online resources."); } case Reference -> { return Localization.lang("A single-volume work of reference such as an encyclopedia or a dictionary."); } case Report -> { return Localization.lang("A technical report, research report, or white paper published by a university or some other institution."); } case Set -> { return Localization.lang("An entry set is a group of entries which are cited as a single reference and listed as a single item in the bibliography."); } case SuppBook -> { return Localization.lang("Supplemental material in a \"Book\". This type is provided for elements such as prefaces, introductions, forewords, afterwords, etc. which often have a generic title only."); } case SuppCollection -> { return Localization.lang("Supplemental material in a \"Collection\"."); } case SuppPeriodical -> { return Localization.lang("Supplemental material in a \"Periodical\". This type may be useful when referring to items such as regular columns, obituaries, letters to the editor, etc. which only have a generic title."); } case Thesis -> { return Localization.lang("A thesis written for an educational institution to satisfy the requirements for a degree."); } case WWW -> { return Localization.lang("An alias for \"Online\", provided for jurabib compatibility."); } case Software -> { return Localization.lang("Computer software. The standard styles will treat this entry type as an alias for \"Misc\"."); } case Dataset -> { return Localization.lang("A data set or a similar collection of (mostly) raw data."); } default -> { return ""; } } } else { return ""; } } }
15,879
47.267477
245
java
null
jabref-main/src/main/java/org/jabref/gui/EntryTypeViewModel.java
package org.jabref.gui; import java.util.Optional; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ListProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleListProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.collections.FXCollections; import javafx.concurrent.Task; import javafx.concurrent.Worker; import org.jabref.gui.externalfiles.ImportHandler; import org.jabref.gui.importer.NewEntryAction; import org.jabref.gui.util.TaskExecutor; import org.jabref.logic.importer.FetcherClientException; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.FetcherServerException; import org.jabref.logic.importer.IdBasedFetcher; import org.jabref.logic.importer.WebFetchers; import org.jabref.logic.importer.fetcher.DoiFetcher; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.model.strings.StringUtil; import org.jabref.model.util.FileUpdateMonitor; import org.jabref.preferences.PreferencesService; import de.saxsys.mvvmfx.utils.validation.FunctionBasedValidator; import de.saxsys.mvvmfx.utils.validation.ValidationMessage; import de.saxsys.mvvmfx.utils.validation.ValidationStatus; import de.saxsys.mvvmfx.utils.validation.Validator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class EntryTypeViewModel { private static final Logger LOGGER = LoggerFactory.getLogger(EntryTypeViewModel.class); private final PreferencesService preferencesService; private final BooleanProperty searchingProperty = new SimpleBooleanProperty(); private final BooleanProperty searchSuccesfulProperty = new SimpleBooleanProperty(); private final ObjectProperty<IdBasedFetcher> selectedItemProperty = new SimpleObjectProperty<>(); private final ListProperty<IdBasedFetcher> fetchers = new SimpleListProperty<>(FXCollections.observableArrayList()); private final StringProperty idText = new SimpleStringProperty(); private final BooleanProperty focusAndSelectAllProperty = new SimpleBooleanProperty(); private Task<Optional<BibEntry>> fetcherWorker = new FetcherWorker(); private final LibraryTab libraryTab; private final DialogService dialogService; private final Validator idFieldValidator; private final StateManager stateManager; private final TaskExecutor taskExecutor; private final FileUpdateMonitor fileUpdateMonitor; public EntryTypeViewModel(PreferencesService preferences, LibraryTab libraryTab, DialogService dialogService, StateManager stateManager, TaskExecutor taskExecutor, FileUpdateMonitor fileUpdateMonitor) { this.libraryTab = libraryTab; this.preferencesService = preferences; this.dialogService = dialogService; this.stateManager = stateManager; this.taskExecutor = taskExecutor; this.fileUpdateMonitor = fileUpdateMonitor; fetchers.addAll(WebFetchers.getIdBasedFetchers( preferences.getImportFormatPreferences(), preferences.getImporterPreferences())); selectedItemProperty.setValue(getLastSelectedFetcher()); idFieldValidator = new FunctionBasedValidator<>( idText, StringUtil::isNotBlank, ValidationMessage.error(Localization.lang("Required field \"%0\" is empty.", Localization.lang("ID")))); } public BooleanProperty searchSuccesfulProperty() { return searchSuccesfulProperty; } public BooleanProperty searchingProperty() { return searchingProperty; } public ObjectProperty<IdBasedFetcher> selectedItemProperty() { return selectedItemProperty; } public ValidationStatus idFieldValidationStatus() { return idFieldValidator.getValidationStatus(); } public StringProperty idTextProperty() { return idText; } public BooleanProperty getFocusAndSelectAllProperty() { return focusAndSelectAllProperty; } public void storeSelectedFetcher() { preferencesService.getGuiPreferences().setLastSelectedIdBasedFetcher(selectedItemProperty.getValue().getName()); } private IdBasedFetcher getLastSelectedFetcher() { return fetchers.stream().filter(fetcher -> fetcher.getName() .equals(preferencesService.getGuiPreferences() .getLastSelectedIdBasedFetcher())) .findFirst() .orElse(new DoiFetcher(preferencesService.getImportFormatPreferences())); } public ListProperty<IdBasedFetcher> fetcherItemsProperty() { return fetchers; } public void stopFetching() { if (fetcherWorker.getState() == Worker.State.RUNNING) { fetcherWorker.cancel(true); } } private class FetcherWorker extends Task<Optional<BibEntry>> { private IdBasedFetcher fetcher = null; private String searchID = ""; @Override protected Optional<BibEntry> call() throws FetcherException { searchingProperty().setValue(true); storeSelectedFetcher(); fetcher = selectedItemProperty().getValue(); searchID = idText.getValue(); if (searchID.isEmpty()) { return Optional.empty(); } return fetcher.performSearchById(searchID); } } public void runFetcherWorker() { searchSuccesfulProperty.set(false); fetcherWorker.run(); fetcherWorker.setOnFailed(event -> { Throwable exception = fetcherWorker.getException(); String fetcherExceptionMessage = exception.getMessage(); String fetcher = selectedItemProperty().getValue().getName(); String searchId = idText.getValue(); if (exception instanceof FetcherClientException) { dialogService.showInformationDialogAndWait(Localization.lang("Failed to import by ID"), Localization.lang("Bibliographic data not found. Cause is likely the client side. Please check connection and identifier for correctness.") + "\n" + fetcherExceptionMessage); } else if (exception instanceof FetcherServerException) { dialogService.showInformationDialogAndWait(Localization.lang("Failed to import by ID"), Localization.lang("Bibliographic data not found. Cause is likely the server side. Please try again later.") + "\n" + fetcherExceptionMessage); } else { dialogService.showInformationDialogAndWait(Localization.lang("Failed to import by ID"), Localization.lang("Error message %0", fetcherExceptionMessage)); } LOGGER.error(String.format("Exception during fetching when using fetcher '%s' with entry id '%s'.", searchId, fetcher), exception); searchingProperty.set(false); fetcherWorker = new FetcherWorker(); }); fetcherWorker.setOnSucceeded(evt -> { Optional<BibEntry> result = fetcherWorker.getValue(); if (result.isPresent()) { final BibEntry entry = result.get(); ImportHandler handler = new ImportHandler( libraryTab.getBibDatabaseContext(), preferencesService, fileUpdateMonitor, libraryTab.getUndoManager(), stateManager, dialogService, taskExecutor); handler.importEntryWithDuplicateCheck(libraryTab.getBibDatabaseContext(), entry); searchSuccesfulProperty.set(true); } else if (StringUtil.isBlank(idText.getValue())) { dialogService.showWarningDialogAndWait(Localization.lang("Empty search ID"), Localization.lang("The given search ID was empty.")); } else { // result is empty String fetcher = selectedItemProperty().getValue().getName(); String searchId = idText.getValue(); // When DOI ID is not found, allow the user to either return to the dialog or add entry manually boolean addEntryFlag = dialogService.showConfirmationDialogAndWait(Localization.lang("Identifier not found"), Localization.lang("Fetcher '%0' did not find an entry for id '%1'.", fetcher, searchId), Localization.lang("Add entry manually"), Localization.lang("Return to dialog")); if (addEntryFlag) { new NewEntryAction( libraryTab.frame(), StandardEntryType.Article, dialogService, preferencesService, stateManager).execute(); searchSuccesfulProperty.set(true); } } fetcherWorker = new FetcherWorker(); focusAndSelectAllProperty.set(true); searchingProperty().setValue(false); }); } }
9,585
43.794393
278
java
null
jabref-main/src/main/java/org/jabref/gui/FXDialog.java
package org.jabref.gui; import javafx.fxml.FXMLLoader; import javafx.scene.control.Alert; import javafx.scene.control.Dialog; import javafx.scene.control.DialogPane; import javafx.scene.image.Image; import javafx.stage.Modality; import javafx.stage.Stage; import org.jabref.gui.icon.IconTheme; import org.jabref.gui.keyboard.KeyBinding; import org.jabref.gui.keyboard.KeyBindingRepository; /** * This class provides a super class for all dialogs implemented in JavaFX. * <p> * To create a custom JavaFX dialog one should create an instance of this class and set a dialog * pane through the inherited {@link Dialog#setDialogPane(DialogPane)} method. * The dialog can be shown via {@link Dialog#show()} or {@link Dialog#showAndWait()}. * <p> * The layout of the pane should be defined in an external fxml file and loaded it via the * {@link FXMLLoader}. */ public class FXDialog extends Alert { public FXDialog(AlertType type, String title, Image image, boolean isModal) { this(type, title, isModal); setDialogIcon(image); } public FXDialog(AlertType type, String title, Image image) { this(type, title, true); setDialogIcon(image); } public FXDialog(AlertType type, String title, boolean isModal) { this(type, isModal); setTitle(title); } public FXDialog(AlertType type, String title) { this(type); setTitle(title); } public FXDialog(AlertType type, boolean isModal) { super(type); setDialogIcon(IconTheme.getJabRefImage()); Stage dialogWindow = getDialogWindow(); dialogWindow.setOnCloseRequest(evt -> this.close()); if (isModal) { initModality(Modality.APPLICATION_MODAL); } else { initModality(Modality.NONE); } dialogWindow.getScene().setOnKeyPressed(event -> { KeyBindingRepository keyBindingRepository = Globals.getKeyPrefs(); if (keyBindingRepository.checkKeyCombinationEquality(KeyBinding.CLOSE, event)) { dialogWindow.close(); } }); } public FXDialog(AlertType type) { this(type, true); } private void setDialogIcon(Image image) { Stage fxDialogWindow = getDialogWindow(); fxDialogWindow.getIcons().add(image); } private Stage getDialogWindow() { return (Stage) getDialogPane().getScene().getWindow(); } }
2,445
29.197531
96
java
null
jabref-main/src/main/java/org/jabref/gui/FallbackExceptionHandler.java
package org.jabref.gui; import org.jabref.gui.util.DefaultTaskExecutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Catch and log any unhandled exceptions. */ public class FallbackExceptionHandler implements Thread.UncaughtExceptionHandler { private static final Logger LOGGER = LoggerFactory.getLogger(FallbackExceptionHandler.class); public static void installExceptionHandler() { Thread.setDefaultUncaughtExceptionHandler(new FallbackExceptionHandler()); } @Override public void uncaughtException(Thread thread, Throwable exception) { LOGGER.error("Uncaught exception occurred in " + thread, exception); DefaultTaskExecutor.runInJavaFXThread(() -> JabRefGUI.getMainFrame() .getDialogService() .showErrorDialogAndWait("Uncaught exception occurred in " + thread, exception) ); } }
932
30.1
103
java
null
jabref-main/src/main/java/org/jabref/gui/Globals.java
package org.jabref.gui; import java.util.Optional; import java.util.UUID; import javafx.stage.Screen; import org.jabref.architecture.AllowedToUseAwt; import org.jabref.gui.keyboard.KeyBindingRepository; import org.jabref.gui.remote.CLIMessageHandler; import org.jabref.gui.theme.ThemeManager; import org.jabref.gui.undo.CountingUndoManager; import org.jabref.gui.util.DefaultFileUpdateMonitor; import org.jabref.gui.util.DefaultTaskExecutor; import org.jabref.gui.util.TaskExecutor; import org.jabref.logic.journals.JournalAbbreviationRepository; import org.jabref.logic.protectedterms.ProtectedTermsLoader; import org.jabref.logic.remote.RemotePreferences; import org.jabref.logic.remote.server.RemoteListenerServerManager; import org.jabref.logic.util.BuildInfo; import org.jabref.model.entry.BibEntryTypesManager; import org.jabref.model.strings.StringUtil; import org.jabref.model.util.FileUpdateMonitor; import org.jabref.preferences.JabRefPreferences; import com.google.common.base.StandardSystemProperty; import com.microsoft.applicationinsights.TelemetryClient; import com.microsoft.applicationinsights.TelemetryConfiguration; import com.microsoft.applicationinsights.telemetry.SessionState; import kong.unirest.Unirest; /** * @deprecated try to use {@link StateManager} and {@link org.jabref.preferences.PreferencesService} */ @Deprecated @AllowedToUseAwt("Requires AWT for headless check") public class Globals { /** * JabRef version info */ public static final BuildInfo BUILD_INFO = new BuildInfo(); public static final RemoteListenerServerManager REMOTE_LISTENER = new RemoteListenerServerManager(); /** * Manager for the state of the GUI. */ public static StateManager stateManager = new StateManager(); public static final TaskExecutor TASK_EXECUTOR = new DefaultTaskExecutor(stateManager); /** * Each test case initializes this field if required */ public static JabRefPreferences prefs; /** * This field is initialized upon startup. * <p> * Only GUI code is allowed to access it, logic code should use dependency injection. */ public static JournalAbbreviationRepository journalAbbreviationRepository; /** * This field is initialized upon startup. * <p> * Only GUI code is allowed to access it, logic code should use dependency injection. */ public static ProtectedTermsLoader protectedTermsLoader; public static CountingUndoManager undoManager = new CountingUndoManager(); public static BibEntryTypesManager entryTypesManager = new BibEntryTypesManager(); private static ClipBoardManager clipBoardManager = null; private static KeyBindingRepository keyBindingRepository; private static ThemeManager themeManager; private static DefaultFileUpdateMonitor fileUpdateMonitor; private static TelemetryClient telemetryClient; private Globals() { } // Key binding preferences public static synchronized KeyBindingRepository getKeyPrefs() { if (keyBindingRepository == null) { keyBindingRepository = prefs.getKeyBindingRepository(); } return keyBindingRepository; } public static synchronized ClipBoardManager getClipboardManager() { if (clipBoardManager == null) { clipBoardManager = new ClipBoardManager(prefs); } return clipBoardManager; } public static synchronized ThemeManager getThemeManager() { if (themeManager == null) { themeManager = new ThemeManager( prefs.getWorkspacePreferences(), getFileUpdateMonitor(), Runnable::run); } return themeManager; } public static synchronized FileUpdateMonitor getFileUpdateMonitor() { if (fileUpdateMonitor == null) { fileUpdateMonitor = new DefaultFileUpdateMonitor(); JabRefExecutorService.INSTANCE.executeInterruptableTask(fileUpdateMonitor, "FileUpdateMonitor"); } return fileUpdateMonitor; } // Background tasks public static void startBackgroundTasks() { // TODO Currently deactivated due to incompatibilities in XML /* if (Globals.prefs.getTelemetryPreferences().shouldCollectTelemetry() && !GraphicsEnvironment.isHeadless()) { startTelemetryClient(); } */ RemotePreferences remotePreferences = prefs.getRemotePreferences(); if (remotePreferences.useRemoteServer()) { Globals.REMOTE_LISTENER.openAndStart(new CLIMessageHandler(prefs, fileUpdateMonitor), remotePreferences.getPort()); } } private static void stopTelemetryClient() { getTelemetryClient().ifPresent(client -> { client.trackSessionState(SessionState.End); client.flush(); }); } private static void startTelemetryClient() { TelemetryConfiguration telemetryConfiguration = TelemetryConfiguration.getActive(); if (!StringUtil.isNullOrEmpty(Globals.BUILD_INFO.azureInstrumentationKey)) { telemetryConfiguration.setInstrumentationKey(Globals.BUILD_INFO.azureInstrumentationKey); } telemetryConfiguration.setTrackingIsDisabled(!Globals.prefs.getTelemetryPreferences().shouldCollectTelemetry()); telemetryClient = new TelemetryClient(telemetryConfiguration); telemetryClient.getContext().getProperties().put("JabRef version", Globals.BUILD_INFO.version.toString()); telemetryClient.getContext().getProperties().put("Java version", StandardSystemProperty.JAVA_VERSION.value()); telemetryClient.getContext().getUser().setId(Globals.prefs.getTelemetryPreferences().getUserId()); telemetryClient.getContext().getSession().setId(UUID.randomUUID().toString()); telemetryClient.getContext().getDevice().setOperatingSystem(StandardSystemProperty.OS_NAME.value()); telemetryClient.getContext().getDevice().setOperatingSystemVersion(StandardSystemProperty.OS_VERSION.value()); telemetryClient.getContext().getDevice().setScreenResolution(Screen.getPrimary().getVisualBounds().toString()); telemetryClient.trackSessionState(SessionState.Start); } public static void shutdownThreadPools() { TASK_EXECUTOR.shutdown(); if (fileUpdateMonitor != null) { fileUpdateMonitor.shutdown(); } JabRefExecutorService.INSTANCE.shutdownEverything(); } public static void stopBackgroundTasks() { stopTelemetryClient(); Unirest.shutDown(); } public static Optional<TelemetryClient> getTelemetryClient() { return Optional.ofNullable(telemetryClient); } }
6,727
38.116279
127
java
null
jabref-main/src/main/java/org/jabref/gui/JabRefDialogService.java
package org.jabref.gui; import java.io.File; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Path; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.function.Consumer; import java.util.stream.Collectors; import javafx.concurrent.Task; import javafx.geometry.Pos; import javafx.print.PrinterJob; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Button; import javafx.scene.control.ButtonBar; import javafx.scene.control.ButtonType; import javafx.scene.control.CheckBox; import javafx.scene.control.ChoiceDialog; import javafx.scene.control.DialogPane; import javafx.scene.control.Label; import javafx.scene.control.TextInputDialog; import javafx.scene.layout.HBox; import javafx.scene.layout.Region; import javafx.scene.layout.VBox; import javafx.stage.DirectoryChooser; import javafx.stage.FileChooser; import javafx.stage.Stage; import javafx.stage.Window; import javafx.util.Duration; import org.jabref.gui.help.ErrorConsoleAction; import org.jabref.gui.icon.IconTheme; import org.jabref.gui.util.BackgroundTask; import org.jabref.gui.util.BaseDialog; import org.jabref.gui.util.DefaultTaskExecutor; import org.jabref.gui.util.DirectoryDialogConfiguration; import org.jabref.gui.util.FileDialogConfiguration; import org.jabref.gui.util.ZipFileChooser; import org.jabref.logic.l10n.Localization; import com.tobiasdiez.easybind.EasyBind; import org.controlsfx.control.Notifications; import org.controlsfx.control.TaskProgressView; import org.controlsfx.control.textfield.CustomPasswordField; import org.controlsfx.dialog.ExceptionDialog; import org.controlsfx.dialog.ProgressDialog; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class provides methods to create default * JavaFX dialogs which will also work on top of Swing * windows. The created dialogs are instances of the * {@link FXDialog} class. The available dialogs in this class * are useful for displaying small information graphic dialogs * rather than complex windows. For more complex dialogs it is * advised to rather create a new sub class of {@link FXDialog}. */ public class JabRefDialogService implements DialogService { // Snackbar dialog maximum size public static final int DIALOG_SIZE_LIMIT = 300; private static final Duration TOAST_MESSAGE_DISPLAY_TIME = Duration.millis(3000); private static final Logger LOGGER = LoggerFactory.getLogger(JabRefDialogService.class); private final Window mainWindow; public JabRefDialogService(Window mainWindow) { this.mainWindow = mainWindow; } private FXDialog createDialog(AlertType type, String title, String content) { FXDialog alert = new FXDialog(type, title, true); alert.setHeaderText(null); alert.setContentText(content); alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE); alert.initOwner(mainWindow); return alert; } private FXDialog createDialogWithOptOut(AlertType type, String title, String content, String optOutMessage, Consumer<Boolean> optOutAction) { FXDialog alert = new FXDialog(type, title, true); // Need to force the alert to layout in order to grab the graphic as we are replacing the dialog pane with a custom pane alert.getDialogPane().applyCss(); Node graphic = alert.getDialogPane().getGraphic(); // Create a new dialog pane that has a checkbox instead of the hide/show details button // Use the supplied callback for the action of the checkbox alert.setDialogPane(new DialogPane() { @Override protected Node createDetailsButton() { CheckBox optOut = new CheckBox(); optOut.setText(optOutMessage); optOut.setOnAction(e -> optOutAction.accept(optOut.isSelected())); return optOut; } }); // Fool the dialog into thinking there is some expandable content; a group won't take up any space if it has no children alert.getDialogPane().setExpandableContent(new Group()); alert.getDialogPane().setExpanded(true); // Reset the dialog graphic using the default style alert.getDialogPane().setGraphic(graphic); alert.setHeaderText(null); alert.setContentText(content); alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE); alert.initOwner(mainWindow); return alert; } public static String shortenDialogMessage(String dialogMessage) { if (dialogMessage.length() < JabRefDialogService.DIALOG_SIZE_LIMIT) { return dialogMessage.trim(); } return (dialogMessage.substring(0, Math.min(dialogMessage.length(), JabRefDialogService.DIALOG_SIZE_LIMIT)) + "...").trim(); } @Override public <T> Optional<T> showChoiceDialogAndWait(String title, String content, String okButtonLabel, T defaultChoice, Collection<T> choices) { ChoiceDialog<T> choiceDialog = new ChoiceDialog<>(defaultChoice, choices); ((Stage) choiceDialog.getDialogPane().getScene().getWindow()).getIcons().add(IconTheme.getJabRefImage()); ButtonType okButtonType = new ButtonType(okButtonLabel, ButtonBar.ButtonData.OK_DONE); choiceDialog.getDialogPane().getButtonTypes().setAll(ButtonType.CANCEL, okButtonType); choiceDialog.setHeaderText(title); choiceDialog.setTitle(title); choiceDialog.setContentText(content); choiceDialog.initOwner(mainWindow); return choiceDialog.showAndWait(); } @Override public Optional<String> showInputDialogAndWait(String title, String content) { TextInputDialog inputDialog = new TextInputDialog(); inputDialog.setHeaderText(title); inputDialog.setContentText(content); inputDialog.initOwner(mainWindow); return inputDialog.showAndWait(); } @Override public Optional<String> showInputDialogWithDefaultAndWait(String title, String content, String defaultValue) { TextInputDialog inputDialog = new TextInputDialog(defaultValue); inputDialog.setHeaderText(title); inputDialog.setContentText(content); inputDialog.initOwner(mainWindow); return inputDialog.showAndWait(); } @Override public void showInformationDialogAndWait(String title, String content) { FXDialog alert = createDialog(AlertType.INFORMATION, title, content); alert.showAndWait(); } @Override public void showWarningDialogAndWait(String title, String content) { FXDialog alert = createDialog(AlertType.WARNING, title, content); alert.showAndWait(); } @Override public void showErrorDialogAndWait(String title, String content) { FXDialog alert = createDialog(AlertType.ERROR, title, content); alert.showAndWait(); } @Override public void showErrorDialogAndWait(String message, Throwable exception) { ExceptionDialog exceptionDialog = new ExceptionDialog(exception); exceptionDialog.getDialogPane().setMaxWidth(mainWindow.getWidth() / 2); exceptionDialog.setHeaderText(message); exceptionDialog.initOwner(mainWindow); exceptionDialog.showAndWait(); } @Override public void showErrorDialogAndWait(String title, String content, Throwable exception) { ExceptionDialog exceptionDialog = new ExceptionDialog(exception); exceptionDialog.setHeaderText(title); exceptionDialog.setContentText(content); exceptionDialog.initOwner(mainWindow); exceptionDialog.showAndWait(); } @Override public void showErrorDialogAndWait(String message) { FXDialog alert = createDialog(AlertType.ERROR, Localization.lang("Error Occurred"), message); alert.showAndWait(); } @Override public boolean showConfirmationDialogAndWait(String title, String content) { FXDialog alert = createDialog(AlertType.CONFIRMATION, title, content); return alert.showAndWait().filter(buttonType -> buttonType == ButtonType.OK).isPresent(); } @Override public boolean showConfirmationDialogAndWait(String title, String content, String okButtonLabel) { FXDialog alert = createDialog(AlertType.CONFIRMATION, title, content); ButtonType okButtonType = new ButtonType(okButtonLabel, ButtonBar.ButtonData.OK_DONE); alert.getButtonTypes().setAll(ButtonType.CANCEL, okButtonType); return alert.showAndWait().filter(buttonType -> buttonType == okButtonType).isPresent(); } @Override public boolean showConfirmationDialogAndWait(String title, String content, String okButtonLabel, String cancelButtonLabel) { FXDialog alert = createDialog(AlertType.CONFIRMATION, title, content); ButtonType okButtonType = new ButtonType(okButtonLabel, ButtonBar.ButtonData.OK_DONE); ButtonType cancelButtonType = new ButtonType(cancelButtonLabel, ButtonBar.ButtonData.NO); alert.getButtonTypes().setAll(okButtonType, cancelButtonType); return alert.showAndWait().filter(buttonType -> buttonType == okButtonType).isPresent(); } @Override public boolean showConfirmationDialogWithOptOutAndWait(String title, String content, String optOutMessage, Consumer<Boolean> optOutAction) { FXDialog alert = createDialogWithOptOut(AlertType.CONFIRMATION, title, content, optOutMessage, optOutAction); alert.getButtonTypes().setAll(ButtonType.YES, ButtonType.NO); return alert.showAndWait().filter(buttonType -> buttonType == ButtonType.YES).isPresent(); } @Override public boolean showConfirmationDialogWithOptOutAndWait(String title, String content, String okButtonLabel, String cancelButtonLabel, String optOutMessage, Consumer<Boolean> optOutAction) { FXDialog alert = createDialogWithOptOut(AlertType.CONFIRMATION, title, content, optOutMessage, optOutAction); ButtonType okButtonType = new ButtonType(okButtonLabel, ButtonBar.ButtonData.YES); ButtonType cancelButtonType = new ButtonType(cancelButtonLabel, ButtonBar.ButtonData.NO); alert.getButtonTypes().setAll(okButtonType, cancelButtonType); return alert.showAndWait().filter(buttonType -> buttonType == okButtonType).isPresent(); } @Override public Optional<ButtonType> showCustomButtonDialogAndWait(AlertType type, String title, String content, ButtonType... buttonTypes) { FXDialog alert = createDialog(type, title, content); alert.getButtonTypes().setAll(buttonTypes); return alert.showAndWait(); } @Override public Optional<ButtonType> showCustomDialogAndWait(String title, DialogPane contentPane, ButtonType... buttonTypes) { FXDialog alert = new FXDialog(AlertType.NONE, title); alert.setDialogPane(contentPane); alert.getButtonTypes().setAll(buttonTypes); alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE); alert.setResizable(true); alert.initOwner(mainWindow); return alert.showAndWait(); } @Override public <R> Optional<R> showCustomDialogAndWait(javafx.scene.control.Dialog<R> dialog) { if (dialog.getOwner() == null) { dialog.initOwner(mainWindow); } return dialog.showAndWait(); } @Override public Optional<String> showPasswordDialogAndWait(String title, String header, String content) { javafx.scene.control.Dialog<String> dialog = new javafx.scene.control.Dialog<>(); dialog.setTitle(title); dialog.setHeaderText(header); CustomPasswordField passwordField = new CustomPasswordField(); HBox box = new HBox(); box.setSpacing(10); box.getChildren().addAll(new Label(content), passwordField); dialog.setTitle(title); dialog.getDialogPane().setContent(box); dialog.getDialogPane().getButtonTypes().addAll(ButtonType.CANCEL, ButtonType.OK); dialog.setResultConverter(dialogButton -> { if (dialogButton == ButtonType.OK) { return passwordField.getText(); } return null; }); return dialog.showAndWait(); } @Override public <V> void showProgressDialog(String title, String content, Task<V> task) { ProgressDialog progressDialog = new ProgressDialog(task); progressDialog.setHeaderText(null); progressDialog.setTitle(title); progressDialog.setContentText(content); progressDialog.setGraphic(null); ((Stage) progressDialog.getDialogPane().getScene().getWindow()).getIcons().add(IconTheme.getJabRefImage()); progressDialog.setOnCloseRequest(evt -> task.cancel()); DialogPane dialogPane = progressDialog.getDialogPane(); dialogPane.getButtonTypes().add(ButtonType.CANCEL); Button cancelButton = (Button) dialogPane.lookupButton(ButtonType.CANCEL); cancelButton.setOnAction(evt -> { task.cancel(); progressDialog.close(); }); progressDialog.initOwner(mainWindow); progressDialog.show(); } @Override public <V> Optional<ButtonType> showBackgroundProgressDialogAndWait(String title, String content, StateManager stateManager) { TaskProgressView<Task<?>> taskProgressView = new TaskProgressView<>(); EasyBind.bindContent(taskProgressView.getTasks(), stateManager.getBackgroundTasks()); taskProgressView.setRetainTasks(false); taskProgressView.setGraphicFactory(BackgroundTask::getIcon); Label message = new Label(content); VBox box = new VBox(taskProgressView, message); DialogPane contentPane = new DialogPane(); contentPane.setContent(box); FXDialog alert = new FXDialog(AlertType.WARNING, title); alert.setDialogPane(contentPane); alert.getButtonTypes().setAll(ButtonType.YES, ButtonType.CANCEL); alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE); alert.setResizable(true); alert.initOwner(mainWindow); stateManager.getAnyTasksThatWillNotBeRecoveredRunning().addListener((observable, oldValue, newValue) -> { if (!newValue) { alert.setResult(ButtonType.YES); alert.close(); } }); return alert.showAndWait(); } @Override public void notify(String message) { LOGGER.info(message); DefaultTaskExecutor.runInJavaFXThread(() -> { Notifications.create() .text(message) .position(Pos.BOTTOM_CENTER) .hideAfter(TOAST_MESSAGE_DISPLAY_TIME) .owner(mainWindow) .threshold(5, Notifications.create() .title(Localization.lang("Last notification")) // TODO: Change to a notification overview instead of event log when that is available. The event log is not that user friendly (different purpose). .text( "(" + Localization.lang("Check the event log to see all notifications") + ")" + "\n\n" + message) .onAction(e -> { ErrorConsoleAction ec = new ErrorConsoleAction(); ec.execute(); })) .hideCloseButton() .show(); }); } @Override public Optional<Path> showFileSaveDialog(FileDialogConfiguration fileDialogConfiguration) { FileChooser chooser = getConfiguredFileChooser(fileDialogConfiguration); File file = chooser.showSaveDialog(mainWindow); Optional.ofNullable(chooser.getSelectedExtensionFilter()).ifPresent(fileDialogConfiguration::setSelectedExtensionFilter); return Optional.ofNullable(file).map(File::toPath); } @Override public Optional<Path> showFileOpenDialog(FileDialogConfiguration fileDialogConfiguration) { FileChooser chooser = getConfiguredFileChooser(fileDialogConfiguration); File file = chooser.showOpenDialog(mainWindow); Optional.ofNullable(chooser.getSelectedExtensionFilter()).ifPresent(fileDialogConfiguration::setSelectedExtensionFilter); return Optional.ofNullable(file).map(File::toPath); } @Override public Optional<Path> showDirectorySelectionDialog(DirectoryDialogConfiguration directoryDialogConfiguration) { DirectoryChooser chooser = getConfiguredDirectoryChooser(directoryDialogConfiguration); File file = chooser.showDialog(mainWindow); return Optional.ofNullable(file).map(File::toPath); } @Override public List<Path> showFileOpenDialogAndGetMultipleFiles(FileDialogConfiguration fileDialogConfiguration) { FileChooser chooser = getConfiguredFileChooser(fileDialogConfiguration); List<File> files = chooser.showOpenMultipleDialog(mainWindow); return files != null ? files.stream().map(File::toPath).collect(Collectors.toList()) : Collections.emptyList(); } private DirectoryChooser getConfiguredDirectoryChooser(DirectoryDialogConfiguration directoryDialogConfiguration) { DirectoryChooser chooser = new DirectoryChooser(); directoryDialogConfiguration.getInitialDirectory().map(Path::toFile).ifPresent(chooser::setInitialDirectory); return chooser; } private FileChooser getConfiguredFileChooser(FileDialogConfiguration fileDialogConfiguration) { FileChooser chooser = new FileChooser(); chooser.getExtensionFilters().addAll(fileDialogConfiguration.getExtensionFilters()); chooser.setSelectedExtensionFilter(fileDialogConfiguration.getDefaultExtension()); chooser.setInitialFileName(fileDialogConfiguration.getInitialFileName()); fileDialogConfiguration.getInitialDirectory().map(Path::toFile).ifPresent(chooser::setInitialDirectory); return chooser; } @Override public boolean showPrintDialog(PrinterJob job) { return job.showPrintDialog(mainWindow); } @Override public Optional<Path> showFileOpenFromArchiveDialog(Path archivePath) throws IOException { try (FileSystem zipFile = FileSystems.newFileSystem(archivePath, (ClassLoader) null)) { return new ZipFileChooser(zipFile).showAndWait(); } catch (NoClassDefFoundError exc) { throw new IOException("Could not instantiate ZIP-archive reader.", exc); } } @Override public void showCustomDialog(BaseDialog<?> aboutDialogView) { if (aboutDialogView.getOwner() == null) { aboutDialogView.initOwner(mainWindow); } aboutDialogView.show(); } }
19,632
43.722096
194
java
null
jabref-main/src/main/java/org/jabref/gui/JabRefExecutorService.java
package org.jabref.gui; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Responsible for managing of all threads (except GUI threads) in JabRef */ public class JabRefExecutorService { public static final JabRefExecutorService INSTANCE = new JabRefExecutorService(); private static final Logger LOGGER = LoggerFactory.getLogger(JabRefExecutorService.class); private final ExecutorService executorService = Executors.newCachedThreadPool(r -> { Thread thread = new Thread(r); thread.setName("JabRef CachedThreadPool"); thread.setUncaughtExceptionHandler(new FallbackExceptionHandler()); return thread; }); private final ExecutorService lowPriorityExecutorService = Executors.newCachedThreadPool(r -> { Thread thread = new Thread(r); thread.setName("JabRef LowPriorityCachedThreadPool"); thread.setUncaughtExceptionHandler(new FallbackExceptionHandler()); return thread; }); private final Timer timer = new Timer("timer", true); private Thread remoteThread; private JabRefExecutorService() { } public void execute(Runnable command) { Objects.requireNonNull(command); executorService.execute(command); } public void executeAndWait(Runnable command) { Objects.requireNonNull(command); Future<?> future = executorService.submit(command); try { future.get(); } catch (InterruptedException e) { LOGGER.debug("The thread is waiting, occupied or interrupted", e); } catch (ExecutionException e) { LOGGER.error("Problem executing command", e); } } /** * Executes a callable task that provides a return value after the calculation is done. * * @param command The task to execute. * @return A Future object that provides the returning value. */ public <T> Future<T> execute(Callable<T> command) { Objects.requireNonNull(command); return executorService.submit(command); } /** * Executes a collection of callable tasks and returns a List of the resulting Future objects after the calculation is done. * * @param tasks The tasks to execute * @return A List of Future objects that provide the returning values. */ public <T> List<Future<T>> executeAll(Collection<Callable<T>> tasks) { Objects.requireNonNull(tasks); try { return executorService.invokeAll(tasks); } catch (InterruptedException exception) { // Ignored return Collections.emptyList(); } } public <T> List<Future<T>> executeAll(Collection<Callable<T>> tasks, int timeout, TimeUnit timeUnit) { Objects.requireNonNull(tasks); try { return executorService.invokeAll(tasks, timeout, timeUnit); } catch (InterruptedException exception) { // Ignored return Collections.emptyList(); } } public void executeInterruptableTask(final Runnable runnable, String taskName) { this.lowPriorityExecutorService.execute(new NamedRunnable(taskName, runnable)); } public void executeInterruptableTaskAndWait(Runnable runnable) { Objects.requireNonNull(runnable); Future<?> future = lowPriorityExecutorService.submit(runnable); try { future.get(); } catch (InterruptedException e) { LOGGER.error("The thread is waiting, occupied or interrupted", e); } catch (ExecutionException e) { LOGGER.error("Problem executing command", e); } } public void startRemoteThread(Thread thread) { if (this.remoteThread != null) { throw new IllegalStateException("Tele thread is already attached"); } else { this.remoteThread = thread; remoteThread.start(); } } public void stopRemoteThread() { if (remoteThread != null) { remoteThread.interrupt(); remoteThread = null; } } public void submit(TimerTask timerTask, long millisecondsDelay) { timer.schedule(timerTask, millisecondsDelay); } /** * Shuts everything down. After termination, this method returns. */ public void shutdownEverything() { stopRemoteThread(); gracefullyShutdown(this.executorService); gracefullyShutdown(this.lowPriorityExecutorService); timer.cancel(); } private static class NamedRunnable implements Runnable { private final String name; private final Runnable task; private NamedRunnable(String name, Runnable runnable) { this.name = name; this.task = runnable; } @Override public void run() { final String orgName = Thread.currentThread().getName(); Thread.currentThread().setName(name); try { task.run(); } finally { Thread.currentThread().setName(orgName); } } } /** * Shuts down the provided executor service by first trying a normal shutdown, then waiting for the shutdown and then forcibly shutting it down. * Returns if the status of the shut down is known. */ public static void gracefullyShutdown(ExecutorService executorService) { try { // This is non-blocking. See https://stackoverflow.com/a/57383461/873282. executorService.shutdown(); if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) { LOGGER.debug("One minute passed, {} still not completed. Trying forced shutdown.", executorService.toString()); // those threads will be interrupted in their current task executorService.shutdownNow(); if (executorService.awaitTermination(60, TimeUnit.SECONDS)) { LOGGER.debug("One minute passed again - forced shutdown of {} worked.", executorService.toString()); } else { LOGGER.error("{} did not terminate", executorService.toString()); } } } catch (InterruptedException ie) { executorService.shutdownNow(); Thread.currentThread().interrupt(); } } }
6,782
33.085427
148
java
null
jabref-main/src/main/java/org/jabref/gui/JabRefFrame.java
package org.jabref.gui; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.TimerTask; import java.util.function.Supplier; import java.util.stream.Collectors; import javafx.application.Platform; import javafx.beans.InvalidationListener; import javafx.beans.Observable; import javafx.beans.binding.Bindings; import javafx.beans.binding.StringBinding; import javafx.collections.transformation.FilteredList; import javafx.concurrent.Task; import javafx.event.ActionEvent; import javafx.geometry.Orientation; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ButtonBar; import javafx.scene.control.ButtonType; import javafx.scene.control.ContextMenu; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.control.ProgressIndicator; import javafx.scene.control.Separator; import javafx.scene.control.SeparatorMenuItem; import javafx.scene.control.SplitPane; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.control.ToolBar; import javafx.scene.control.Tooltip; import javafx.scene.control.skin.TabPaneSkin; import javafx.scene.input.Dragboard; import javafx.scene.input.KeyEvent; import javafx.scene.input.TransferMode; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; import javafx.scene.layout.Region; import javafx.scene.layout.VBox; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; import org.jabref.gui.actions.ActionFactory; import org.jabref.gui.actions.ActionHelper; import org.jabref.gui.actions.SimpleCommand; import org.jabref.gui.actions.StandardActions; import org.jabref.gui.auximport.NewSubLibraryAction; import org.jabref.gui.bibtexextractor.ExtractBibtexAction; import org.jabref.gui.citationkeypattern.GenerateCitationKeyAction; import org.jabref.gui.cleanup.CleanupAction; import org.jabref.gui.copyfiles.CopyFilesAction; import org.jabref.gui.desktop.JabRefDesktop; import org.jabref.gui.documentviewer.ShowDocumentViewerAction; import org.jabref.gui.duplicationFinder.DuplicateSearch; import org.jabref.gui.edit.CopyMoreAction; import org.jabref.gui.edit.EditAction; import org.jabref.gui.edit.ManageKeywordsAction; import org.jabref.gui.edit.OpenBrowserAction; import org.jabref.gui.edit.ReplaceStringAction; import org.jabref.gui.edit.automaticfiededitor.AutomaticFieldEditorAction; import org.jabref.gui.entryeditor.OpenEntryEditorAction; import org.jabref.gui.entryeditor.PreviewSwitchAction; import org.jabref.gui.exporter.ExportCommand; import org.jabref.gui.exporter.ExportToClipboardAction; import org.jabref.gui.exporter.SaveAction; import org.jabref.gui.exporter.SaveAllAction; import org.jabref.gui.exporter.SaveDatabaseAction; import org.jabref.gui.exporter.WriteMetadataToPdfAction; import org.jabref.gui.externalfiles.AutoLinkFilesAction; import org.jabref.gui.externalfiles.DownloadFullTextAction; import org.jabref.gui.externalfiles.FindUnlinkedFilesAction; import org.jabref.gui.help.AboutAction; import org.jabref.gui.help.ErrorConsoleAction; import org.jabref.gui.help.HelpAction; import org.jabref.gui.help.SearchForUpdateAction; import org.jabref.gui.icon.IconTheme; import org.jabref.gui.importer.GenerateEntryFromIdDialog; import org.jabref.gui.importer.ImportCommand; import org.jabref.gui.importer.ImportEntriesDialog; import org.jabref.gui.importer.NewDatabaseAction; import org.jabref.gui.importer.NewEntryAction; import org.jabref.gui.importer.actions.OpenDatabaseAction; import org.jabref.gui.importer.fetcher.LookupIdentifierAction; import org.jabref.gui.integrity.IntegrityCheckAction; import org.jabref.gui.journals.AbbreviateAction; import org.jabref.gui.keyboard.KeyBinding; import org.jabref.gui.keyboard.KeyBindingRepository; import org.jabref.gui.libraryproperties.LibraryPropertiesAction; import org.jabref.gui.menus.FileHistoryMenu; import org.jabref.gui.mergeentries.MergeEntriesAction; import org.jabref.gui.preferences.ShowPreferencesAction; import org.jabref.gui.preview.CopyCitationAction; import org.jabref.gui.push.PushToApplicationCommand; import org.jabref.gui.search.GlobalSearchBar; import org.jabref.gui.search.RebuildFulltextSearchIndexAction; import org.jabref.gui.shared.ConnectToSharedDatabaseCommand; import org.jabref.gui.shared.PullChangesFromSharedAction; import org.jabref.gui.sidepane.SidePane; import org.jabref.gui.sidepane.SidePaneType; import org.jabref.gui.slr.EditExistingStudyAction; import org.jabref.gui.slr.ExistingStudySearchAction; import org.jabref.gui.slr.StartNewStudyAction; import org.jabref.gui.specialfields.SpecialFieldMenuItemFactory; import org.jabref.gui.texparser.ParseLatexAction; import org.jabref.gui.theme.ThemeManager; import org.jabref.gui.undo.CountingUndoManager; import org.jabref.gui.undo.UndoRedoAction; import org.jabref.gui.util.BackgroundTask; import org.jabref.gui.util.DefaultTaskExecutor; import org.jabref.gui.util.TaskExecutor; import org.jabref.logic.autosaveandbackup.AutosaveManager; import org.jabref.logic.autosaveandbackup.BackupManager; import org.jabref.logic.citationstyle.CitationStyleOutputFormat; import org.jabref.logic.help.HelpFile; import org.jabref.logic.importer.IdFetcher; import org.jabref.logic.importer.ImportCleanup; import org.jabref.logic.importer.ParserResult; import org.jabref.logic.importer.WebFetchers; import org.jabref.logic.l10n.Localization; import org.jabref.logic.shared.DatabaseLocation; import org.jabref.logic.undo.AddUndoableActionEvent; import org.jabref.logic.undo.UndoChangeEvent; import org.jabref.logic.undo.UndoRedoEvent; import org.jabref.logic.util.OS; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.SpecialField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.model.groups.GroupTreeNode; import org.jabref.model.util.FileUpdateMonitor; import org.jabref.preferences.PreferencesService; import org.jabref.preferences.TelemetryPreferences; import com.google.common.eventbus.Subscribe; import com.tobiasdiez.easybind.EasyBind; import com.tobiasdiez.easybind.EasyObservableList; import com.tobiasdiez.easybind.Subscription; import org.controlsfx.control.PopOver; import org.controlsfx.control.TaskProgressView; import org.fxmisc.richtext.CodeArea; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The main window of the application. */ public class JabRefFrame extends BorderPane { public static final String FRAME_TITLE = "JabRef"; private static final Logger LOGGER = LoggerFactory.getLogger(JabRefFrame.class); private final SplitPane splitPane = new SplitPane(); private final PreferencesService prefs = Globals.prefs; private final GlobalSearchBar globalSearchBar; private final FileHistoryMenu fileHistory; @SuppressWarnings({"FieldCanBeLocal"}) private EasyObservableList<BibDatabaseContext> openDatabaseList; private final Stage mainStage; private final StateManager stateManager; private final CountingUndoManager undoManager; private final DialogService dialogService; private final FileUpdateMonitor fileUpdateMonitor; private final PushToApplicationCommand pushToApplicationCommand; private SidePane sidePane; private TabPane tabbedPane; private PopOver progressViewPopOver; private PopOver entryFromIdPopOver; private Subscription dividerSubscription; private final TaskExecutor taskExecutor; public JabRefFrame(Stage mainStage) { this.mainStage = mainStage; this.stateManager = Globals.stateManager; this.dialogService = new JabRefDialogService(mainStage); this.undoManager = Globals.undoManager; this.fileUpdateMonitor = Globals.getFileUpdateMonitor(); this.globalSearchBar = new GlobalSearchBar(this, stateManager, prefs, undoManager, dialogService); this.pushToApplicationCommand = new PushToApplicationCommand(stateManager, dialogService, prefs); this.fileHistory = new FileHistoryMenu(prefs.getGuiPreferences().getFileHistory(), dialogService, getOpenDatabaseAction()); this.taskExecutor = Globals.TASK_EXECUTOR; this.setOnKeyTyped(key -> { if (this.fileHistory.isShowing()) { if (this.fileHistory.openFileByKey(key)) { this.fileHistory.getParentMenu().hide(); } } }); } private void initDragAndDrop() { Tab dndIndicator = new Tab(Localization.lang("Open files..."), null); dndIndicator.getStyleClass().add("drop"); EasyBind.subscribe(tabbedPane.skinProperty(), skin -> { if (!(skin instanceof TabPaneSkin)) { return; } // Add drag and drop listeners to JabRefFrame this.getScene().setOnDragOver(event -> { if (DragAndDropHelper.hasBibFiles(event.getDragboard())) { event.acceptTransferModes(TransferMode.ANY); if (!tabbedPane.getTabs().contains(dndIndicator)) { tabbedPane.getTabs().add(dndIndicator); } event.consume(); } else { tabbedPane.getTabs().remove(dndIndicator); } // Accept drag entries from MainTable if (event.getDragboard().hasContent(DragAndDropDataFormats.ENTRIES)) { event.acceptTransferModes(TransferMode.COPY); event.consume(); } }); this.getScene().setOnDragEntered(event -> { // It is necessary to setOnDragOver for newly opened tabs // drag'n'drop on tabs covered dnd on tabbedPane, so dnd on tabs should contain all dnds on tabbedPane tabbedPane.lookupAll(".tab").forEach(destinationTabNode -> { destinationTabNode.setOnDragOver(tabDragEvent -> { if (DragAndDropHelper.hasBibFiles(tabDragEvent.getDragboard()) || DragAndDropHelper.hasGroups(tabDragEvent.getDragboard())) { tabDragEvent.acceptTransferModes(TransferMode.ANY); if (!tabbedPane.getTabs().contains(dndIndicator)) { tabbedPane.getTabs().add(dndIndicator); } event.consume(); } else { tabbedPane.getTabs().remove(dndIndicator); } if (tabDragEvent.getDragboard().hasContent(DragAndDropDataFormats.ENTRIES)) { tabDragEvent.acceptTransferModes(TransferMode.COPY); tabDragEvent.consume(); } }); destinationTabNode.setOnDragExited(event1 -> tabbedPane.getTabs().remove(dndIndicator)); destinationTabNode.setOnDragDropped(tabDragEvent -> { Dragboard dragboard = tabDragEvent.getDragboard(); if (DragAndDropHelper.hasBibFiles(dragboard)) { tabbedPane.getTabs().remove(dndIndicator); List<Path> bibFiles = DragAndDropHelper.getBibFiles(dragboard); OpenDatabaseAction openDatabaseAction = this.getOpenDatabaseAction(); openDatabaseAction.openFiles(bibFiles); tabDragEvent.setDropCompleted(true); tabDragEvent.consume(); } else { for (Tab libraryTab : tabbedPane.getTabs()) { if (libraryTab.getId().equals(destinationTabNode.getId()) && !tabbedPane.getSelectionModel().getSelectedItem().equals(libraryTab)) { LibraryTab destinationLibraryTab = (LibraryTab) libraryTab; if (DragAndDropHelper.hasGroups(dragboard)) { List<String> groupPathToSources = DragAndDropHelper.getGroups(dragboard); copyRootNode(destinationLibraryTab); GroupTreeNode destinationLibraryGroupRoot = destinationLibraryTab .getBibDatabaseContext() .getMetaData() .getGroups().get(); for (String pathToSource : groupPathToSources) { GroupTreeNode groupTreeNodeToCopy = getCurrentLibraryTab() .getBibDatabaseContext() .getMetaData() .getGroups() .get() .getChildByPath(pathToSource) .get(); copyGroupTreeNode((LibraryTab) libraryTab, destinationLibraryGroupRoot, groupTreeNodeToCopy); } return; } destinationLibraryTab.dropEntry(stateManager.getLocalDragboard().getBibEntries()); } } tabDragEvent.consume(); } }); }); event.consume(); }); this.getScene().setOnDragExited(event -> tabbedPane.getTabs().remove(dndIndicator)); this.getScene().setOnDragDropped(event -> { tabbedPane.getTabs().remove(dndIndicator); List<Path> bibFiles = DragAndDropHelper.getBibFiles(event.getDragboard()); OpenDatabaseAction openDatabaseAction = this.getOpenDatabaseAction(); openDatabaseAction.openFiles(bibFiles); event.setDropCompleted(true); event.consume(); }); }); } private void initKeyBindings() { addEventFilter(KeyEvent.KEY_PRESSED, event -> { Optional<KeyBinding> keyBinding = Globals.getKeyPrefs().mapToKeyBinding(event); if (keyBinding.isPresent()) { switch (keyBinding.get()) { case FOCUS_ENTRY_TABLE: getCurrentLibraryTab().getMainTable().requestFocus(); event.consume(); break; case FOCUS_GROUP_LIST: sidePane.getSidePaneComponent(SidePaneType.GROUPS).requestFocus(); event.consume(); break; case NEXT_LIBRARY: tabbedPane.getSelectionModel().selectNext(); event.consume(); break; case PREVIOUS_LIBRARY: tabbedPane.getSelectionModel().selectPrevious(); event.consume(); break; case SEARCH: getGlobalSearchBar().focus(); break; case NEW_ARTICLE: new NewEntryAction(this, StandardEntryType.Article, dialogService, prefs, stateManager).execute(); break; case NEW_BOOK: new NewEntryAction(this, StandardEntryType.Book, dialogService, prefs, stateManager).execute(); break; case NEW_INBOOK: new NewEntryAction(this, StandardEntryType.InBook, dialogService, prefs, stateManager).execute(); break; case NEW_MASTERSTHESIS: new NewEntryAction(this, StandardEntryType.MastersThesis, dialogService, prefs, stateManager).execute(); break; case NEW_PHDTHESIS: new NewEntryAction(this, StandardEntryType.PhdThesis, dialogService, prefs, stateManager).execute(); break; case NEW_PROCEEDINGS: new NewEntryAction(this, StandardEntryType.Proceedings, dialogService, prefs, stateManager).execute(); break; case NEW_TECHREPORT: new NewEntryAction(this, StandardEntryType.TechReport, dialogService, prefs, stateManager).execute(); break; case NEW_UNPUBLISHED: new NewEntryAction(this, StandardEntryType.Unpublished, dialogService, prefs, stateManager).execute(); break; case NEW_INPROCEEDINGS: new NewEntryAction(this, StandardEntryType.InProceedings, dialogService, prefs, stateManager).execute(); break; case PASTE: if (OS.OS_X) { // Workaround for a jdk issue that executes paste twice when using cmd+v in a TextField // Extra workaround for CodeArea, which does not inherit from TextInputControl if (!(stateManager.getFocusOwner().isPresent() && (stateManager.getFocusOwner().get() instanceof CodeArea))) { event.consume(); } break; } default: } } }); } private void initShowTrackingNotification() { if (prefs.getTelemetryPreferences().shouldAskToCollectTelemetry()) { JabRefExecutorService.INSTANCE.submit(new TimerTask() { @Override public void run() { DefaultTaskExecutor.runInJavaFXThread(JabRefFrame.this::showTrackingNotification); } }, 60000); // run in one minute } } private void showTrackingNotification() { TelemetryPreferences telemetryPreferences = prefs.getTelemetryPreferences(); boolean shouldCollect = telemetryPreferences.shouldCollectTelemetry(); if (!telemetryPreferences.shouldCollectTelemetry()) { shouldCollect = dialogService.showConfirmationDialogAndWait( Localization.lang("Telemetry: Help make JabRef better"), Localization.lang("To improve the user experience, we would like to collect anonymous statistics on the features you use. We will only record what features you access and how often you do it. We will neither collect any personal data nor the content of bibliographic items. If you choose to allow data collection, you can later disable it via Options -> Preferences -> General."), Localization.lang("Share anonymous statistics"), Localization.lang("Don't share")); } telemetryPreferences.setCollectTelemetry(shouldCollect); telemetryPreferences.setAskToCollectTelemetry(false); } /** * The MacAdapter calls this method when a "BIB" file has been double-clicked from the Finder. */ public void openAction(String filePath) { Path file = Path.of(filePath); getOpenDatabaseAction().openFile(file); } /** * The MacAdapter calls this method when "About" is selected from the application menu. */ public void about() { new HelpAction(HelpFile.CONTENTS, dialogService).execute(); } /** * Tears down all things started by JabRef * <p> * FIXME: Currently some threads remain and therefore hinder JabRef to be closed properly * * @param filenames the filenames of all currently opened files - used for storing them if prefs openLastEdited is * set to true */ private void tearDownJabRef(List<String> filenames) { if (prefs.getWorkspacePreferences().shouldOpenLastEdited()) { // Here we store the names of all current files. If there is no current file, we remove any // previously stored filename. if (filenames.isEmpty()) { prefs.getGuiPreferences().getLastFilesOpened().clear(); } else { Path focusedDatabase = getCurrentLibraryTab().getBibDatabaseContext() .getDatabasePath() .orElse(null); prefs.getGuiPreferences().setLastFilesOpened(filenames); prefs.getGuiPreferences().setLastFocusedFile(focusedDatabase); } } prefs.flush(); } /** * General info dialog. The MacAdapter calls this method when "Quit" is selected from the application menu, Cmd-Q * is pressed, or "Quit" is selected from the Dock. The function returns a boolean indicating if quitting is ok or * not. * <p> * Non-OSX JabRef calls this when choosing "Quit" from the menu * <p> * SIDE EFFECT: tears down JabRef * * @return true if the user chose to quit; false otherwise */ public boolean quit() { // First ask if the user really wants to close, if there are still background tasks running /* It is important to wait for unfinished background tasks before checking if a save-operation is needed, because the background tasks may make changes themselves that need saving. */ if (stateManager.getAnyTasksThatWillNotBeRecoveredRunning().getValue()) { Optional<ButtonType> shouldClose = dialogService.showBackgroundProgressDialogAndWait( Localization.lang("Please wait..."), Localization.lang("Waiting for background tasks to finish. Quit anyway?"), stateManager); if (!(shouldClose.isPresent() && (shouldClose.get() == ButtonType.YES))) { return false; } } // Then ask if the user really wants to close, if the library has not been saved since last save. List<String> filenames = new ArrayList<>(); for (int i = 0; i < tabbedPane.getTabs().size(); i++) { LibraryTab libraryTab = getLibraryTabAt(i); final BibDatabaseContext context = libraryTab.getBibDatabaseContext(); if (libraryTab.isModified() && (context.getLocation() == DatabaseLocation.LOCAL)) { tabbedPane.getSelectionModel().select(i); if (!confirmClose(libraryTab)) { return false; } } else if (context.getLocation() == DatabaseLocation.SHARED) { context.convertToLocalDatabase(); context.getDBMSSynchronizer().closeSharedDatabase(); context.clearDBMSSynchronizer(); } AutosaveManager.shutdown(context); BackupManager.shutdown(context, prefs.getFilePreferences().getBackupDirectory(), prefs.getFilePreferences().shouldCreateBackup()); context.getDatabasePath().map(Path::toAbsolutePath).map(Path::toString).ifPresent(filenames::add); } WaitForSaveFinishedDialog waitForSaveFinishedDialog = new WaitForSaveFinishedDialog(dialogService); waitForSaveFinishedDialog.showAndWait(getLibraryTabs()); // Good bye! tearDownJabRef(filenames); Platform.exit(); return true; } private void initLayout() { setId("frame"); VBox head = new VBox(createMenu(), createToolbar()); head.setSpacing(0d); setTop(head); splitPane.getItems().addAll(tabbedPane); SplitPane.setResizableWithParent(sidePane, false); sidePane.getChildren().addListener((InvalidationListener) c -> updateSidePane()); updateSidePane(); // We need to wait with setting the divider since it gets reset a few times during the initial set-up mainStage.showingProperty().addListener(new InvalidationListener() { @Override public void invalidated(Observable observable) { if (mainStage.isShowing()) { Platform.runLater(() -> { setDividerPosition(); observable.removeListener(this); }); } } }); setCenter(splitPane); } private void updateSidePane() { if (sidePane.getChildren().isEmpty()) { if (dividerSubscription != null) { dividerSubscription.unsubscribe(); } splitPane.getItems().remove(sidePane); } else { if (!splitPane.getItems().contains(sidePane)) { splitPane.getItems().add(0, sidePane); setDividerPosition(); } } } private void setDividerPosition() { if (mainStage.isShowing() && !sidePane.getChildren().isEmpty()) { splitPane.setDividerPositions(prefs.getGuiPreferences().getSidePaneWidth() / splitPane.getWidth()); dividerSubscription = EasyBind.subscribe(sidePane.widthProperty(), width -> prefs.getGuiPreferences().setSidePaneWidth(width.doubleValue())); } } private Node createToolbar() { final ActionFactory factory = new ActionFactory(Globals.getKeyPrefs()); final Region leftSpacer = new Region(); final Region rightSpacer = new Region(); final Button pushToApplicationButton = factory.createIconButton(pushToApplicationCommand.getAction(), pushToApplicationCommand); pushToApplicationCommand.registerReconfigurable(pushToApplicationButton); // Setup Toolbar ToolBar toolBar = new ToolBar( new HBox( factory.createIconButton(StandardActions.NEW_LIBRARY, new NewDatabaseAction(this, prefs)), factory.createIconButton(StandardActions.OPEN_LIBRARY, new OpenDatabaseAction(this, prefs, dialogService, stateManager, fileUpdateMonitor)), factory.createIconButton(StandardActions.SAVE_LIBRARY, new SaveAction(SaveAction.SaveMethod.SAVE, this, prefs, stateManager))), leftSpacer, globalSearchBar, rightSpacer, new HBox( factory.createIconButton(StandardActions.NEW_ARTICLE, new NewEntryAction(this, StandardEntryType.Article, dialogService, prefs, stateManager)), factory.createIconButton(StandardActions.NEW_ENTRY, new NewEntryAction(this, dialogService, prefs, stateManager)), createNewEntryFromIdButton(), factory.createIconButton(StandardActions.NEW_ENTRY_FROM_PLAIN_TEXT, new ExtractBibtexAction(dialogService, prefs, stateManager)), factory.createIconButton(StandardActions.DELETE_ENTRY, new EditAction(StandardActions.DELETE_ENTRY, this, stateManager))), new Separator(Orientation.VERTICAL), new HBox( factory.createIconButton(StandardActions.UNDO, new UndoRedoAction(StandardActions.UNDO, this, dialogService, stateManager)), factory.createIconButton(StandardActions.REDO, new UndoRedoAction(StandardActions.REDO, this, dialogService, stateManager)), factory.createIconButton(StandardActions.CUT, new EditAction(StandardActions.CUT, this, stateManager)), factory.createIconButton(StandardActions.COPY, new EditAction(StandardActions.COPY, this, stateManager)), factory.createIconButton(StandardActions.PASTE, new EditAction(StandardActions.PASTE, this, stateManager))), new Separator(Orientation.VERTICAL), new HBox( pushToApplicationButton, factory.createIconButton(StandardActions.GENERATE_CITE_KEYS, new GenerateCitationKeyAction(this, dialogService, stateManager, taskExecutor, prefs)), factory.createIconButton(StandardActions.CLEANUP_ENTRIES, new CleanupAction(this, prefs, dialogService, stateManager))), new Separator(Orientation.VERTICAL), new HBox( createTaskIndicator()), new Separator(Orientation.VERTICAL), new HBox( factory.createIconButton(StandardActions.OPEN_GITHUB, new OpenBrowserAction("https://github.com/JabRef/jabref", dialogService)))); leftSpacer.setPrefWidth(50); leftSpacer.setMinWidth(Region.USE_PREF_SIZE); leftSpacer.setMaxWidth(Region.USE_PREF_SIZE); HBox.setHgrow(globalSearchBar, Priority.ALWAYS); HBox.setHgrow(rightSpacer, Priority.SOMETIMES); toolBar.getStyleClass().add("mainToolbar"); return toolBar; } /** * Returns the indexed LibraryTab. * * @param i Index of base */ public LibraryTab getLibraryTabAt(int i) { return (LibraryTab) tabbedPane.getTabs().get(i); } /** * Returns a list of all LibraryTabs in this frame. */ public List<LibraryTab> getLibraryTabs() { return tabbedPane.getTabs().stream() .filter(LibraryTab.class::isInstance) .map(LibraryTab.class::cast) .collect(Collectors.toList()); } public void showLibraryTabAt(int i) { tabbedPane.getSelectionModel().select(i); } public void showLibraryTab(LibraryTab libraryTab) { tabbedPane.getSelectionModel().select(libraryTab); } public void init() { sidePane = new SidePane(prefs, Globals.journalAbbreviationRepository, taskExecutor, dialogService, stateManager, undoManager); tabbedPane = new TabPane(); tabbedPane.setTabDragPolicy(TabPane.TabDragPolicy.REORDER); initLayout(); initKeyBindings(); initDragAndDrop(); // Bind global state FilteredList<Tab> filteredTabs = new FilteredList<>(tabbedPane.getTabs()); filteredTabs.setPredicate(LibraryTab.class::isInstance); // This variable cannot be inlined, since otherwise the list created by EasyBind is being garbage collected openDatabaseList = EasyBind.map(filteredTabs, tab -> ((LibraryTab) tab).getBibDatabaseContext()); EasyBind.bindContent(stateManager.getOpenDatabases(), openDatabaseList); // the binding for stateManager.activeDatabaseProperty() is at org.jabref.gui.LibraryTab.onDatabaseLoadingSucceed // Subscribe to the search EasyBind.subscribe(stateManager.activeSearchQueryProperty(), query -> { if (prefs.getSearchPreferences().shouldKeepSearchString()) { for (LibraryTab tab : getLibraryTabs()) { tab.setCurrentSearchQuery(query); } } else { if (getCurrentLibraryTab() != null) { getCurrentLibraryTab().setCurrentSearchQuery(query); } } }); // Wait for the scene to be created, otherwise focusOwnerProperty is not provided Platform.runLater(() -> stateManager.focusOwnerProperty().bind( EasyBind.map(mainStage.getScene().focusOwnerProperty(), Optional::ofNullable))); EasyBind.subscribe(tabbedPane.getSelectionModel().selectedItemProperty(), selectedTab -> { if (selectedTab instanceof LibraryTab libraryTab) { stateManager.setActiveDatabase(libraryTab.getBibDatabaseContext()); } else if (selectedTab == null) { // All databases are closed stateManager.setActiveDatabase(null); } }); /* * The following state listener makes sure focus is registered with the * correct database when the user switches tabs. Without this, * cut/paste/copy operations would sometimes occur in the wrong tab. */ EasyBind.subscribe(tabbedPane.getSelectionModel().selectedItemProperty(), tab -> { if (!(tab instanceof LibraryTab libraryTab)) { stateManager.setSelectedEntries(Collections.emptyList()); mainStage.titleProperty().unbind(); mainStage.setTitle(FRAME_TITLE); return; } // Poor-mans binding to global state stateManager.setSelectedEntries(libraryTab.getSelectedEntries()); // Update active search query when switching between databases if (prefs.getSearchPreferences().shouldKeepSearchString() && libraryTab.getCurrentSearchQuery().isEmpty() && stateManager.activeSearchQueryProperty().get().isPresent()) { // apply search query also when opening a new library and keep search string is activated libraryTab.setCurrentSearchQuery(stateManager.activeSearchQueryProperty().get()); } else { stateManager.activeSearchQueryProperty().set(libraryTab.getCurrentSearchQuery()); } // Update search autocompleter with information for the correct database: libraryTab.updateSearchManager(); libraryTab.getUndoManager().postUndoRedoEvent(); libraryTab.getMainTable().requestFocus(); // Set window title - copy tab title StringBinding windowTitle = Bindings.createStringBinding( () -> libraryTab.textProperty().getValue() + " \u2013 " + FRAME_TITLE, libraryTab.textProperty()); mainStage.titleProperty().bind(windowTitle); }); initShowTrackingNotification(); } /** * Returns the currently viewed BasePanel. */ public LibraryTab getCurrentLibraryTab() { if ((tabbedPane == null) || (tabbedPane.getSelectionModel().getSelectedItem() == null)) { return null; } return (LibraryTab) tabbedPane.getSelectionModel().getSelectedItem(); } /** * @return the BasePanel count. */ public int getBasePanelCount() { return tabbedPane.getTabs().size(); } /** * @deprecated do not operate on tabs but on BibDatabaseContexts */ @Deprecated public TabPane getTabbedPane() { return tabbedPane; } private MenuBar createMenu() { ActionFactory factory = new ActionFactory(Globals.getKeyPrefs()); Menu file = new Menu(Localization.lang("File")); Menu edit = new Menu(Localization.lang("Edit")); Menu library = new Menu(Localization.lang("Library")); Menu quality = new Menu(Localization.lang("Quality")); Menu lookup = new Menu(Localization.lang("Lookup")); Menu view = new Menu(Localization.lang("View")); Menu tools = new Menu(Localization.lang("Tools")); Menu help = new Menu(Localization.lang("Help")); file.getItems().addAll( factory.createMenuItem(StandardActions.NEW_LIBRARY, new NewDatabaseAction(this, prefs)), factory.createMenuItem(StandardActions.OPEN_LIBRARY, getOpenDatabaseAction()), fileHistory, factory.createMenuItem(StandardActions.SAVE_LIBRARY, new SaveAction(SaveAction.SaveMethod.SAVE, this, prefs, stateManager)), factory.createMenuItem(StandardActions.SAVE_LIBRARY_AS, new SaveAction(SaveAction.SaveMethod.SAVE_AS, this, prefs, stateManager)), factory.createMenuItem(StandardActions.SAVE_ALL, new SaveAllAction(this, prefs)), factory.createMenuItem(StandardActions.CLOSE_LIBRARY, new CloseDatabaseAction()), new SeparatorMenuItem(), factory.createSubMenu(StandardActions.IMPORT, factory.createMenuItem(StandardActions.IMPORT_INTO_CURRENT_LIBRARY, new ImportCommand(this, false, prefs, stateManager, fileUpdateMonitor)), factory.createMenuItem(StandardActions.IMPORT_INTO_NEW_LIBRARY, new ImportCommand(this, true, prefs, stateManager, fileUpdateMonitor))), factory.createSubMenu(StandardActions.EXPORT, factory.createMenuItem(StandardActions.EXPORT_ALL, new ExportCommand(ExportCommand.ExportMethod.EXPORT_ALL, this, stateManager, dialogService, prefs)), factory.createMenuItem(StandardActions.EXPORT_SELECTED, new ExportCommand(ExportCommand.ExportMethod.EXPORT_SELECTED, this, stateManager, dialogService, prefs)), factory.createMenuItem(StandardActions.SAVE_SELECTED_AS_PLAIN_BIBTEX, new SaveAction(SaveAction.SaveMethod.SAVE_SELECTED, this, prefs, stateManager))), new SeparatorMenuItem(), factory.createSubMenu(StandardActions.REMOTE_DB, factory.createMenuItem(StandardActions.CONNECT_TO_SHARED_DB, new ConnectToSharedDatabaseCommand(this)), factory.createMenuItem(StandardActions.PULL_CHANGES_FROM_SHARED_DB, new PullChangesFromSharedAction(stateManager))), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.SHOW_PREFS, new ShowPreferencesAction(this, taskExecutor)), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.QUIT, new CloseAction()) ); edit.getItems().addAll( factory.createMenuItem(StandardActions.UNDO, new UndoRedoAction(StandardActions.UNDO, this, dialogService, stateManager)), factory.createMenuItem(StandardActions.REDO, new UndoRedoAction(StandardActions.REDO, this, dialogService, stateManager)), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.CUT, new EditAction(StandardActions.CUT, this, stateManager)), factory.createMenuItem(StandardActions.COPY, new EditAction(StandardActions.COPY, this, stateManager)), factory.createSubMenu(StandardActions.COPY_MORE, factory.createMenuItem(StandardActions.COPY_TITLE, new CopyMoreAction(StandardActions.COPY_TITLE, dialogService, stateManager, Globals.getClipboardManager(), prefs, Globals.journalAbbreviationRepository)), factory.createMenuItem(StandardActions.COPY_KEY, new CopyMoreAction(StandardActions.COPY_KEY, dialogService, stateManager, Globals.getClipboardManager(), prefs, Globals.journalAbbreviationRepository)), factory.createMenuItem(StandardActions.COPY_CITE_KEY, new CopyMoreAction(StandardActions.COPY_CITE_KEY, dialogService, stateManager, Globals.getClipboardManager(), prefs, Globals.journalAbbreviationRepository)), factory.createMenuItem(StandardActions.COPY_KEY_AND_TITLE, new CopyMoreAction(StandardActions.COPY_KEY_AND_TITLE, dialogService, stateManager, Globals.getClipboardManager(), prefs, Globals.journalAbbreviationRepository)), factory.createMenuItem(StandardActions.COPY_KEY_AND_LINK, new CopyMoreAction(StandardActions.COPY_KEY_AND_LINK, dialogService, stateManager, Globals.getClipboardManager(), prefs, Globals.journalAbbreviationRepository)), factory.createMenuItem(StandardActions.COPY_CITATION_PREVIEW, new CopyCitationAction(CitationStyleOutputFormat.HTML, dialogService, stateManager, Globals.getClipboardManager(), Globals.TASK_EXECUTOR, prefs, Globals.journalAbbreviationRepository)), factory.createMenuItem(StandardActions.EXPORT_SELECTED_TO_CLIPBOARD, new ExportToClipboardAction(dialogService, stateManager, Globals.getClipboardManager(), Globals.TASK_EXECUTOR, prefs))), factory.createMenuItem(StandardActions.PASTE, new EditAction(StandardActions.PASTE, this, stateManager)), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.REPLACE_ALL, new ReplaceStringAction(this, stateManager)), factory.createMenuItem(StandardActions.GENERATE_CITE_KEYS, new GenerateCitationKeyAction(this, dialogService, stateManager, taskExecutor, prefs)), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.MANAGE_KEYWORDS, new ManageKeywordsAction(stateManager)), factory.createMenuItem(StandardActions.AUTOMATIC_FIELD_EDITOR, new AutomaticFieldEditorAction(stateManager, dialogService))); SeparatorMenuItem specialFieldsSeparator = new SeparatorMenuItem(); specialFieldsSeparator.visibleProperty().bind(prefs.getSpecialFieldsPreferences().specialFieldsEnabledProperty()); edit.getItems().addAll( specialFieldsSeparator, // ToDo: SpecialField needs the active BasePanel to mark it as changed. // Refactor BasePanel, should mark the BibDatabaseContext or the UndoManager as dirty instead! SpecialFieldMenuItemFactory.createSpecialFieldMenu(SpecialField.RANKING, factory, this, dialogService, prefs, undoManager, stateManager), SpecialFieldMenuItemFactory.getSpecialFieldSingleItem(SpecialField.RELEVANCE, factory, this, dialogService, prefs, undoManager, stateManager), SpecialFieldMenuItemFactory.getSpecialFieldSingleItem(SpecialField.QUALITY, factory, this, dialogService, prefs, undoManager, stateManager), SpecialFieldMenuItemFactory.getSpecialFieldSingleItem(SpecialField.PRINTED, factory, this, dialogService, prefs, undoManager, stateManager), SpecialFieldMenuItemFactory.createSpecialFieldMenu(SpecialField.PRIORITY, factory, this, dialogService, prefs, undoManager, stateManager), SpecialFieldMenuItemFactory.createSpecialFieldMenu(SpecialField.READ_STATUS, factory, this, dialogService, prefs, undoManager, stateManager)); edit.addEventHandler(ActionEvent.ACTION, event -> { // Work around for mac only issue, where cmd+v on a dialogue triggers the paste action of menu item, resulting in addition of the pasted content in the MainTable. // If the mainscreen is not focused, the actions captured by menu are consumed. if (OS.OS_X && !mainStage.focusedProperty().get()) { event.consume(); } }); // @formatter:off library.getItems().addAll( factory.createMenuItem(StandardActions.NEW_ENTRY, new NewEntryAction(this, dialogService, prefs, stateManager)), factory.createMenuItem(StandardActions.NEW_ENTRY_FROM_PLAIN_TEXT, new ExtractBibtexAction(dialogService, prefs, stateManager)), factory.createMenuItem(StandardActions.DELETE_ENTRY, new EditAction(StandardActions.DELETE_ENTRY, this, stateManager)), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.LIBRARY_PROPERTIES, new LibraryPropertiesAction(stateManager)) ); quality.getItems().addAll( factory.createMenuItem(StandardActions.FIND_DUPLICATES, new DuplicateSearch(this, dialogService, stateManager, prefs)), factory.createMenuItem(StandardActions.MERGE_ENTRIES, new MergeEntriesAction(dialogService, stateManager, prefs.getBibEntryPreferences())), factory.createMenuItem(StandardActions.CHECK_INTEGRITY, new IntegrityCheckAction(this, stateManager, Globals.TASK_EXECUTOR)), factory.createMenuItem(StandardActions.CLEANUP_ENTRIES, new CleanupAction(this, this.prefs, dialogService, stateManager)), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.SET_FILE_LINKS, new AutoLinkFilesAction(dialogService, prefs, stateManager, undoManager, Globals.TASK_EXECUTOR)), new SeparatorMenuItem(), factory.createSubMenu(StandardActions.ABBREVIATE, factory.createMenuItem(StandardActions.ABBREVIATE_DEFAULT, new AbbreviateAction(StandardActions.ABBREVIATE_DEFAULT, this, dialogService, stateManager, prefs.getJournalAbbreviationPreferences())), factory.createMenuItem(StandardActions.ABBREVIATE_DOTLESS, new AbbreviateAction(StandardActions.ABBREVIATE_DOTLESS, this, dialogService, stateManager, prefs.getJournalAbbreviationPreferences())), factory.createMenuItem(StandardActions.ABBREVIATE_SHORTEST_UNIQUE, new AbbreviateAction(StandardActions.ABBREVIATE_SHORTEST_UNIQUE, this, dialogService, stateManager, prefs.getJournalAbbreviationPreferences()))), factory.createMenuItem(StandardActions.UNABBREVIATE, new AbbreviateAction(StandardActions.UNABBREVIATE, this, dialogService, stateManager, prefs.getJournalAbbreviationPreferences())) ); Menu lookupIdentifiers = factory.createSubMenu(StandardActions.LOOKUP_DOC_IDENTIFIER); for (IdFetcher<?> fetcher : WebFetchers.getIdFetchers(prefs.getImportFormatPreferences())) { LookupIdentifierAction<?> identifierAction = new LookupIdentifierAction<>(this, fetcher, stateManager, undoManager); lookupIdentifiers.getItems().add(factory.createMenuItem(identifierAction.getAction(), identifierAction)); } lookup.getItems().addAll( lookupIdentifiers, factory.createMenuItem(StandardActions.DOWNLOAD_FULL_TEXT, new DownloadFullTextAction(dialogService, stateManager, prefs)), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.FIND_UNLINKED_FILES, new FindUnlinkedFilesAction(dialogService, stateManager)) ); final MenuItem pushToApplicationMenuItem = factory.createMenuItem(pushToApplicationCommand.getAction(), pushToApplicationCommand); pushToApplicationCommand.registerReconfigurable(pushToApplicationMenuItem); tools.getItems().addAll( factory.createMenuItem(StandardActions.PARSE_LATEX, new ParseLatexAction(stateManager)), factory.createMenuItem(StandardActions.NEW_SUB_LIBRARY_FROM_AUX, new NewSubLibraryAction(this, stateManager)), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.WRITE_METADATA_TO_PDF, new WriteMetadataToPdfAction(stateManager, Globals.entryTypesManager, prefs.getFieldPreferences(), dialogService, taskExecutor, prefs.getFilePreferences(), prefs.getXmpPreferences())), factory.createMenuItem(StandardActions.COPY_LINKED_FILES, new CopyFilesAction(dialogService, prefs, stateManager)), new SeparatorMenuItem(), createSendSubMenu(factory, dialogService, stateManager, prefs), pushToApplicationMenuItem, new SeparatorMenuItem(), // Systematic Literature Review (SLR) factory.createMenuItem(StandardActions.START_NEW_STUDY, new StartNewStudyAction(this, fileUpdateMonitor, taskExecutor, prefs, stateManager)), factory.createMenuItem(StandardActions.EDIT_EXISTING_STUDY, new EditExistingStudyAction(this.dialogService, this.stateManager)), factory.createMenuItem(StandardActions.UPDATE_SEARCH_RESULTS_OF_STUDY, new ExistingStudySearchAction(this, this.getOpenDatabaseAction(), this.getDialogService(), fileUpdateMonitor, Globals.TASK_EXECUTOR, prefs, stateManager)), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.REBUILD_FULLTEXT_SEARCH_INDEX, new RebuildFulltextSearchIndexAction(stateManager, this::getCurrentLibraryTab, dialogService, prefs.getFilePreferences())) ); SidePaneType webSearchPane = SidePaneType.WEB_SEARCH; SidePaneType groupsPane = SidePaneType.GROUPS; SidePaneType openOfficePane = SidePaneType.OPEN_OFFICE; view.getItems().addAll( factory.createCheckMenuItem(webSearchPane.getToggleAction(), sidePane.getToggleCommandFor(webSearchPane), sidePane.paneVisibleBinding(webSearchPane)), factory.createCheckMenuItem(groupsPane.getToggleAction(), sidePane.getToggleCommandFor(groupsPane), sidePane.paneVisibleBinding(groupsPane)), factory.createCheckMenuItem(openOfficePane.getToggleAction(), sidePane.getToggleCommandFor(openOfficePane), sidePane.paneVisibleBinding(openOfficePane)), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.NEXT_PREVIEW_STYLE, new PreviewSwitchAction(PreviewSwitchAction.Direction.NEXT, this, stateManager)), factory.createMenuItem(StandardActions.PREVIOUS_PREVIEW_STYLE, new PreviewSwitchAction(PreviewSwitchAction.Direction.PREVIOUS, this, stateManager)), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.SHOW_PDF_VIEWER, new ShowDocumentViewerAction(stateManager, prefs)), factory.createMenuItem(StandardActions.EDIT_ENTRY, new OpenEntryEditorAction(this, stateManager)), factory.createMenuItem(StandardActions.OPEN_CONSOLE, new OpenConsoleAction(stateManager, prefs, dialogService)) ); help.getItems().addAll( factory.createMenuItem(StandardActions.HELP, new HelpAction(HelpFile.CONTENTS, dialogService)), factory.createMenuItem(StandardActions.OPEN_FORUM, new OpenBrowserAction("http://discourse.jabref.org/", dialogService)), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.ERROR_CONSOLE, new ErrorConsoleAction()), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.DONATE, new OpenBrowserAction("https://donations.jabref.org", dialogService)), factory.createMenuItem(StandardActions.SEARCH_FOR_UPDATES, new SearchForUpdateAction(Globals.BUILD_INFO, prefs.getInternalPreferences(), dialogService, Globals.TASK_EXECUTOR)), factory.createSubMenu(StandardActions.WEB_MENU, factory.createMenuItem(StandardActions.OPEN_WEBPAGE, new OpenBrowserAction("https://jabref.org/", dialogService)), factory.createMenuItem(StandardActions.OPEN_BLOG, new OpenBrowserAction("https://blog.jabref.org/", dialogService)), factory.createMenuItem(StandardActions.OPEN_FACEBOOK, new OpenBrowserAction("https://www.facebook.com/JabRef/", dialogService)), factory.createMenuItem(StandardActions.OPEN_TWITTER, new OpenBrowserAction("https://twitter.com/jabref_org", dialogService)), factory.createMenuItem(StandardActions.OPEN_GITHUB, new OpenBrowserAction("https://github.com/JabRef/jabref", dialogService)), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.OPEN_DEV_VERSION_LINK, new OpenBrowserAction("https://builds.jabref.org/master/", dialogService)), factory.createMenuItem(StandardActions.OPEN_CHANGELOG, new OpenBrowserAction("https://github.com/JabRef/jabref/blob/main/CHANGELOG.md", dialogService)) ), factory.createMenuItem(StandardActions.ABOUT, new AboutAction()) ); // @formatter:on MenuBar menu = new MenuBar(); menu.getStyleClass().add("mainMenu"); menu.getMenus().addAll( file, edit, library, quality, lookup, tools, view, help); menu.setUseSystemMenuBar(true); return menu; } private Button createNewEntryFromIdButton() { Button newEntryFromIdButton = new Button(); newEntryFromIdButton.setGraphic(IconTheme.JabRefIcons.IMPORT.getGraphicNode()); newEntryFromIdButton.getStyleClass().setAll("icon-button"); newEntryFromIdButton.setFocusTraversable(false); newEntryFromIdButton.disableProperty().bind(ActionHelper.needsDatabase(stateManager).not()); newEntryFromIdButton.setOnMouseClicked(event -> { GenerateEntryFromIdDialog entryFromId = new GenerateEntryFromIdDialog(getCurrentLibraryTab(), dialogService, prefs, taskExecutor, stateManager); if (entryFromIdPopOver == null) { entryFromIdPopOver = new PopOver(entryFromId.getDialogPane()); entryFromIdPopOver.setTitle(Localization.lang("Import by ID")); entryFromIdPopOver.setArrowLocation(PopOver.ArrowLocation.TOP_CENTER); entryFromIdPopOver.setContentNode(entryFromId.getDialogPane()); entryFromIdPopOver.show(newEntryFromIdButton); entryFromId.setEntryFromIdPopOver(entryFromIdPopOver); } else if (entryFromIdPopOver.isShowing()) { entryFromIdPopOver.hide(); } else { entryFromIdPopOver.setContentNode(entryFromId.getDialogPane()); entryFromIdPopOver.show(newEntryFromIdButton); entryFromId.setEntryFromIdPopOver(entryFromIdPopOver); } }); newEntryFromIdButton.setTooltip(new Tooltip(Localization.lang("Import by ID"))); return newEntryFromIdButton; } private Group createTaskIndicator() { ProgressIndicator indicator = new ProgressIndicator(); indicator.getStyleClass().add("progress-indicatorToolbar"); indicator.progressProperty().bind(stateManager.getTasksProgress()); Tooltip someTasksRunning = new Tooltip(Localization.lang("Background Tasks are running")); Tooltip noTasksRunning = new Tooltip(Localization.lang("Background Tasks are done")); indicator.setTooltip(noTasksRunning); stateManager.getAnyTaskRunning().addListener((observable, oldValue, newValue) -> { if (newValue) { indicator.setTooltip(someTasksRunning); } else { indicator.setTooltip(noTasksRunning); } }); /* The label of the indicator cannot be removed with styling. Therefore, hide it and clip it to a square of (width x width) each time width is updated. */ indicator.widthProperty().addListener((observable, oldValue, newValue) -> { /* The indeterminate spinner is wider than the determinate spinner. We must make sure they are the same width for the clipping to result in a square of the same size always. */ if (!indicator.isIndeterminate()) { indicator.setPrefWidth(newValue.doubleValue()); } if (newValue.doubleValue() > 0) { Rectangle clip = new Rectangle(newValue.doubleValue(), newValue.doubleValue()); indicator.setClip(clip); } }); indicator.setOnMouseClicked(event -> { TaskProgressView<Task<?>> taskProgressView = new TaskProgressView<>(); EasyBind.bindContent(taskProgressView.getTasks(), stateManager.getBackgroundTasks()); taskProgressView.setRetainTasks(true); taskProgressView.setGraphicFactory(BackgroundTask::getIcon); if (progressViewPopOver == null) { progressViewPopOver = new PopOver(taskProgressView); progressViewPopOver.setTitle(Localization.lang("Background Tasks")); progressViewPopOver.setArrowLocation(PopOver.ArrowLocation.RIGHT_TOP); progressViewPopOver.setContentNode(taskProgressView); progressViewPopOver.show(indicator); } else if (progressViewPopOver.isShowing()) { progressViewPopOver.hide(); } else { progressViewPopOver.setContentNode(taskProgressView); progressViewPopOver.show(indicator); } }); return new Group(indicator); } /** * Might be called when a user asks JabRef at the command line * i) to import a file or * ii) to open a .bib file */ public void addParserResult(ParserResult parserResult, boolean focusPanel) { if (parserResult.toOpenTab()) { // Add the entries to the open tab. LibraryTab libraryTab = getCurrentLibraryTab(); if (libraryTab == null) { // There is no open tab to add to, so we create a new tab: addTab(parserResult.getDatabaseContext(), focusPanel); } else { addImportedEntries(libraryTab, parserResult); } } else { // only add tab if library is not already open Optional<LibraryTab> libraryTab = getLibraryTabs().stream() .filter(p -> p.getBibDatabaseContext() .getDatabasePath() .equals(parserResult.getPath())) .findFirst(); if (libraryTab.isPresent()) { tabbedPane.getSelectionModel().select(libraryTab.get()); } else { addTab(parserResult.getDatabaseContext(), focusPanel); } } } /** * This method causes all open LibraryTabs to set up their tables anew. When called from PreferencesDialogViewModel, * this updates to the new settings. We need to notify all tabs about the changes to avoid problems when changing * the column set. */ public void setupAllTables() { tabbedPane.getTabs().forEach(tab -> { if (tab instanceof LibraryTab libraryTab && (libraryTab.getDatabase() != null)) { DefaultTaskExecutor.runInJavaFXThread(libraryTab::setupMainPanel); } }); } private ContextMenu createTabContextMenuFor(LibraryTab tab, KeyBindingRepository keyBindingRepository) { ContextMenu contextMenu = new ContextMenu(); ActionFactory factory = new ActionFactory(keyBindingRepository); contextMenu.getItems().addAll( factory.createMenuItem(StandardActions.LIBRARY_PROPERTIES, new LibraryPropertiesAction(tab::getBibDatabaseContext, stateManager)), factory.createMenuItem(StandardActions.OPEN_DATABASE_FOLDER, new OpenDatabaseFolder(tab::getBibDatabaseContext)), factory.createMenuItem(StandardActions.OPEN_CONSOLE, new OpenConsoleAction(tab::getBibDatabaseContext, stateManager, prefs, dialogService)), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.CLOSE_LIBRARY, new CloseDatabaseAction(tab)), factory.createMenuItem(StandardActions.CLOSE_OTHER_LIBRARIES, new CloseOthersDatabaseAction(tab)), factory.createMenuItem(StandardActions.CLOSE_ALL_LIBRARIES, new CloseAllDatabaseAction())); return contextMenu; } public void addTab(LibraryTab libraryTab, boolean raisePanel) { tabbedPane.getTabs().add(libraryTab); libraryTab.setOnCloseRequest(event -> { libraryTab.cancelLoading(); closeTab(libraryTab); event.consume(); }); libraryTab.setContextMenu(createTabContextMenuFor(libraryTab, Globals.getKeyPrefs())); if (raisePanel) { tabbedPane.getSelectionModel().select(libraryTab); } libraryTab.getUndoManager().registerListener(new UndoRedoEventManager()); } /** * Opens a new tab with existing data. * Asynchronous loading is done at {@link org.jabref.gui.LibraryTab#createLibraryTab(BackgroundTask, Path, PreferencesService, StateManager, JabRefFrame, ThemeManager)}. */ public LibraryTab addTab(BibDatabaseContext databaseContext, boolean raisePanel) { Objects.requireNonNull(databaseContext); LibraryTab libraryTab = new LibraryTab(databaseContext, this, prefs, stateManager, fileUpdateMonitor); addTab(libraryTab, raisePanel); return libraryTab; } /** * Opens the import inspection dialog to let the user decide which of the given entries to import. * * @param panel The BasePanel to add to. * @param parserResult The entries to add. */ private void addImportedEntries(final LibraryTab panel, final ParserResult parserResult) { BackgroundTask<ParserResult> task = BackgroundTask.wrap(() -> parserResult); ImportCleanup cleanup = new ImportCleanup(panel.getBibDatabaseContext().getMode()); cleanup.doPostCleanup(parserResult.getDatabase().getEntries()); ImportEntriesDialog dialog = new ImportEntriesDialog(panel.getBibDatabaseContext(), task); dialog.setTitle(Localization.lang("Import")); dialogService.showCustomDialogAndWait(dialog); } public FileHistoryMenu getFileHistory() { return fileHistory; } /** * Ask if the user really wants to close the given database. * Offers to save or discard the changes -- or return to the library * * @return <code>true</code> if the user choose to close the database */ private boolean confirmClose(LibraryTab libraryTab) { String filename = libraryTab.getBibDatabaseContext() .getDatabasePath() .map(Path::toAbsolutePath) .map(Path::toString) .orElse(Localization.lang("untitled")); ButtonType saveChanges = new ButtonType(Localization.lang("Save changes"), ButtonBar.ButtonData.YES); ButtonType discardChanges = new ButtonType(Localization.lang("Discard changes"), ButtonBar.ButtonData.NO); ButtonType returnToLibrary = new ButtonType(Localization.lang("Return to library"), ButtonBar.ButtonData.CANCEL_CLOSE); Optional<ButtonType> response = dialogService.showCustomButtonDialogAndWait(Alert.AlertType.CONFIRMATION, Localization.lang("Save before closing"), Localization.lang("Library '%0' has changed.", filename), saveChanges, discardChanges, returnToLibrary); if (response.isEmpty()) { return true; } ButtonType buttonType = response.get(); if (buttonType.equals(returnToLibrary)) { return false; } if (buttonType.equals(saveChanges)) { try { SaveDatabaseAction saveAction = new SaveDatabaseAction(libraryTab, prefs, Globals.entryTypesManager); if (saveAction.save()) { return true; } // The action was either canceled or unsuccessful. dialogService.notify(Localization.lang("Unable to save library")); } catch (Throwable ex) { LOGGER.error("A problem occurred when trying to save the file", ex); dialogService.showErrorDialogAndWait(Localization.lang("Save library"), Localization.lang("Could not save file."), ex); } // Save was cancelled or an error occurred. return false; } if (buttonType.equals(discardChanges)) { BackupManager.discardBackup(libraryTab.getBibDatabaseContext(), prefs.getFilePreferences().getBackupDirectory()); return true; } return false; } private void closeTab(LibraryTab libraryTab) { // empty tab without database if (libraryTab == null) { return; } final BibDatabaseContext context = libraryTab.getBibDatabaseContext(); if (libraryTab.isModified() && (context.getLocation() == DatabaseLocation.LOCAL)) { if (confirmClose(libraryTab)) { removeTab(libraryTab); } else { return; } } else if (context.getLocation() == DatabaseLocation.SHARED) { context.convertToLocalDatabase(); context.getDBMSSynchronizer().closeSharedDatabase(); context.clearDBMSSynchronizer(); removeTab(libraryTab); } else { removeTab(libraryTab); } AutosaveManager.shutdown(context); BackupManager.shutdown(context, prefs.getFilePreferences().getBackupDirectory(), prefs.getFilePreferences().shouldCreateBackup()); } private void removeTab(LibraryTab libraryTab) { DefaultTaskExecutor.runInJavaFXThread(() -> { libraryTab.cleanUp(); tabbedPane.getTabs().remove(libraryTab); }); } public void closeCurrentTab() { removeTab(getCurrentLibraryTab()); } public OpenDatabaseAction getOpenDatabaseAction() { return new OpenDatabaseAction(this, prefs, dialogService, stateManager, fileUpdateMonitor); } public GlobalSearchBar getGlobalSearchBar() { return globalSearchBar; } public CountingUndoManager getUndoManager() { return undoManager; } public DialogService getDialogService() { return dialogService; } private void copyGroupTreeNode(LibraryTab destinationLibraryTab, GroupTreeNode parent, GroupTreeNode groupTreeNodeToCopy) { List<BibEntry> allEntries = getCurrentLibraryTab() .getBibDatabaseContext() .getEntries(); // add groupTreeNodeToCopy to the parent-- in the first run that will the source/main GroupTreeNode GroupTreeNode copiedNode = parent.addSubgroup(groupTreeNodeToCopy.copyNode().getGroup()); // add all entries of a groupTreeNode to the new library. destinationLibraryTab.dropEntry(groupTreeNodeToCopy.getEntriesInGroup(allEntries)); // List of all children of groupTreeNodeToCopy List<GroupTreeNode> children = groupTreeNodeToCopy.getChildren(); if (!children.isEmpty()) { // use recursion to add all subgroups of the original groupTreeNodeToCopy for (GroupTreeNode child : children) { copyGroupTreeNode(destinationLibraryTab, copiedNode, child); } } } private void copyRootNode(LibraryTab destinationLibraryTab) { if (!destinationLibraryTab.getBibDatabaseContext().getMetaData().getGroups().isEmpty()) { return; } // a root (all entries) GroupTreeNode GroupTreeNode currentLibraryGroupRoot = getCurrentLibraryTab().getBibDatabaseContext() .getMetaData() .getGroups() .get() .copyNode(); // add currentLibraryGroupRoot to the Library if it does not have a root. destinationLibraryTab.getBibDatabaseContext() .getMetaData() .setGroups(currentLibraryGroupRoot); } private Menu createSendSubMenu(ActionFactory factory, DialogService dialogService, StateManager stateManager, PreferencesService preferencesService) { Menu sendMenu = factory.createMenu(StandardActions.SEND); sendMenu.getItems().addAll( factory.createMenuItem(StandardActions.SEND_AS_EMAIL, new SendAsStandardEmailAction(dialogService, preferencesService, stateManager)), factory.createMenuItem(StandardActions.SEND_TO_KINDLE, new SendAsKindleEmailAction(dialogService, preferencesService, stateManager)) ); return sendMenu; } /** * The action concerned with closing the window. */ private class CloseAction extends SimpleCommand { @Override public void execute() { quit(); } } private class CloseDatabaseAction extends SimpleCommand { private final LibraryTab libraryTab; public CloseDatabaseAction(LibraryTab libraryTab) { this.libraryTab = libraryTab; } /** * Using this constructor will result in executing the command on the currently open library tab */ public CloseDatabaseAction() { this(null); } @Override public void execute() { closeTab(Optional.ofNullable(libraryTab).orElse(getCurrentLibraryTab())); } } private class CloseOthersDatabaseAction extends SimpleCommand { private final LibraryTab libraryTab; public CloseOthersDatabaseAction(LibraryTab libraryTab) { this.libraryTab = libraryTab; this.executable.bind(ActionHelper.isOpenMultiDatabase(tabbedPane)); } @Override public void execute() { LibraryTab toKeepLibraryTab = Optional.of(libraryTab).get(); for (Tab tab : tabbedPane.getTabs()) { LibraryTab libraryTab = (LibraryTab) tab; if (libraryTab != toKeepLibraryTab) { closeTab(libraryTab); } } } } private class CloseAllDatabaseAction extends SimpleCommand { @Override public void execute() { for (Tab tab : tabbedPane.getTabs()) { closeTab((LibraryTab) tab); } } } private class OpenDatabaseFolder extends SimpleCommand { private final Supplier<BibDatabaseContext> databaseContext; public OpenDatabaseFolder(Supplier<BibDatabaseContext> databaseContext) { this.databaseContext = databaseContext; } @Override public void execute() { Optional.of(databaseContext.get()).flatMap(BibDatabaseContext::getDatabasePath).ifPresent(path -> { try { JabRefDesktop.openFolderAndSelectFile(path, prefs, dialogService); } catch (IOException e) { LOGGER.info("Could not open folder", e); } }); } } private class UndoRedoEventManager { @Subscribe public void listen(UndoRedoEvent event) { updateTexts(event); JabRefFrame.this.getCurrentLibraryTab().updateEntryEditorIfShowing(); } @Subscribe public void listen(AddUndoableActionEvent event) { updateTexts(event); } private void updateTexts(UndoChangeEvent event) { /* TODO SwingUtilities.invokeLater(() -> { undo.putValue(Action.SHORT_DESCRIPTION, event.getUndoDescription()); undo.setEnabled(event.isCanUndo()); redo.putValue(Action.SHORT_DESCRIPTION, event.getRedoDescription()); redo.setEnabled(event.isCanRedo()); }); */ } } }
72,093
48.72
400
java
null
jabref-main/src/main/java/org/jabref/gui/JabRefGUI.java
package org.jabref.gui; import java.nio.file.Path; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import javafx.application.Platform; import javafx.scene.Scene; import javafx.scene.input.KeyEvent; import javafx.stage.Screen; import javafx.stage.Stage; import org.jabref.gui.help.VersionWorker; import org.jabref.gui.icon.IconTheme; import org.jabref.gui.importer.ParserResultWarningDialog; import org.jabref.gui.importer.actions.OpenDatabaseAction; import org.jabref.gui.keyboard.TextInputKeyBindings; import org.jabref.gui.shared.SharedDatabaseUIManager; import org.jabref.logic.importer.ParserResult; import org.jabref.logic.l10n.Localization; import org.jabref.logic.net.ProxyRegisterer; import org.jabref.logic.shared.DatabaseNotSupportedException; import org.jabref.logic.shared.exception.InvalidDBMSConnectionPropertiesException; import org.jabref.logic.shared.exception.NotASharedDatabaseException; import org.jabref.logic.util.WebViewStore; import org.jabref.model.strings.StringUtil; import org.jabref.model.util.FileUpdateMonitor; import org.jabref.preferences.GuiPreferences; import org.jabref.preferences.PreferencesService; import com.airhacks.afterburner.injection.Injector; import impl.org.controlsfx.skin.DecorationPane; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class JabRefGUI { private static final Logger LOGGER = LoggerFactory.getLogger(JabRefGUI.class); private static JabRefFrame mainFrame; private final PreferencesService preferencesService; private final FileUpdateMonitor fileUpdateMonitor; private final List<ParserResult> bibDatabases; private final boolean isBlank; private boolean correctedWindowPos; private final List<ParserResult> failed = new ArrayList<>(); private final List<ParserResult> toOpenTab = new ArrayList<>(); public JabRefGUI(Stage mainStage, List<ParserResult> databases, boolean isBlank, PreferencesService preferencesService, FileUpdateMonitor fileUpdateMonitor) { this.bibDatabases = databases; this.isBlank = isBlank; this.preferencesService = preferencesService; this.fileUpdateMonitor = fileUpdateMonitor; this.correctedWindowPos = false; WebViewStore.init(); mainFrame = new JabRefFrame(mainStage); openWindow(mainStage); new VersionWorker(Globals.BUILD_INFO.version, mainFrame.getDialogService(), Globals.TASK_EXECUTOR, preferencesService.getInternalPreferences()) .checkForNewVersionDelayed(); setupProxy(); } private void setupProxy() { if (!preferencesService.getProxyPreferences().shouldUseProxy() || !preferencesService.getProxyPreferences().shouldUseAuthentication()) { return; } if (preferencesService.getProxyPreferences().shouldPersistPassword() && StringUtil.isNotBlank(preferencesService.getProxyPreferences().getPassword())) { ProxyRegisterer.register(preferencesService.getProxyPreferences()); return; } DialogService dialogService = Injector.instantiateModelOrService(DialogService.class); Optional<String> password = dialogService.showPasswordDialogAndWait( Localization.lang("Proxy configuration"), Localization.lang("Proxy requires password"), Localization.lang("Password")); if (password.isPresent()) { preferencesService.getProxyPreferences().setPassword(password.get()); ProxyRegisterer.register(preferencesService.getProxyPreferences()); } else { LOGGER.warn("No proxy password specified"); } } private void openWindow(Stage mainStage) { LOGGER.debug("Initializing frame"); mainFrame.init(); GuiPreferences guiPreferences = preferencesService.getGuiPreferences(); // Set the min-width and min-height for the main window mainStage.setMinHeight(330); mainStage.setMinWidth(580); // Restore window location and/or maximised state if (guiPreferences.isWindowMaximised()) { mainStage.setMaximized(true); } else if ((Screen.getScreens().size() == 1) && isWindowPositionOutOfBounds()) { // corrects the Window, if it is outside the mainscreen LOGGER.debug("The Jabref window is outside the main screen"); mainStage.setX(0); mainStage.setY(0); mainStage.setWidth(1024); mainStage.setHeight(768); correctedWindowPos = true; } else { mainStage.setX(guiPreferences.getPositionX()); mainStage.setY(guiPreferences.getPositionY()); mainStage.setWidth(guiPreferences.getSizeX()); mainStage.setHeight(guiPreferences.getSizeY()); } debugLogWindowState(mainStage); // We create a decoration pane ourselves for performance reasons // (otherwise it has to be injected later, leading to a complete redraw/relayout of the complete scene) DecorationPane root = new DecorationPane(); root.getChildren().add(JabRefGUI.mainFrame); Scene scene = new Scene(root, 800, 800); Globals.getThemeManager().installCss(scene); // Handle TextEditor key bindings scene.addEventFilter(KeyEvent.KEY_PRESSED, event -> TextInputKeyBindings.call(scene, event)); mainStage.setTitle(JabRefFrame.FRAME_TITLE); mainStage.getIcons().addAll(IconTheme.getLogoSetFX()); mainStage.setScene(scene); mainStage.show(); mainStage.setOnCloseRequest(event -> { if (!correctedWindowPos) { // saves the window position only if its not corrected -> the window will rest at the old Position, // if the external Screen is connected again. saveWindowState(mainStage); } boolean reallyQuit = mainFrame.quit(); if (!reallyQuit) { event.consume(); } }); Platform.runLater(this::openDatabases); if (!(fileUpdateMonitor.isActive())) { getMainFrame().getDialogService() .showErrorDialogAndWait(Localization.lang("Unable to monitor file changes. Please close files " + "and processes and restart. You may encounter errors if you continue " + "with this session.")); } } private void openDatabases() { // If the option is enabled, open the last edited libraries, if any. if (!isBlank && preferencesService.getWorkspacePreferences().shouldOpenLastEdited()) { openLastEditedDatabases(); } // From here on, the libraries provided by command line arguments are treated // Remove invalid databases List<ParserResult> invalidDatabases = bibDatabases.stream() .filter(ParserResult::isInvalid) .toList(); failed.addAll(invalidDatabases); bibDatabases.removeAll(invalidDatabases); // passed file (we take the first one) should be focused Path focusedFile = bibDatabases.stream() .findFirst() .flatMap(ParserResult::getPath) .orElse(preferencesService.getGuiPreferences() .getLastFocusedFile()) .toAbsolutePath(); // Add all bibDatabases databases to the frame: boolean first = false; for (ParserResult pr : bibDatabases) { // Define focused tab if (pr.getPath().filter(path -> path.toAbsolutePath().equals(focusedFile)).isPresent()) { first = true; } if (pr.getDatabase().isShared()) { try { new SharedDatabaseUIManager(mainFrame, preferencesService, fileUpdateMonitor) .openSharedDatabaseFromParserResult(pr); } catch (SQLException | DatabaseNotSupportedException | InvalidDBMSConnectionPropertiesException | NotASharedDatabaseException e) { pr.getDatabaseContext().clearDatabasePath(); // do not open the original file pr.getDatabase().clearSharedDatabaseID(); LOGGER.error("Connection error", e); mainFrame.getDialogService().showErrorDialogAndWait( Localization.lang("Connection error"), Localization.lang("A local copy will be opened."), e); } toOpenTab.add(pr); } else if (pr.toOpenTab()) { // things to be appended to an opened tab should be done after opening all tabs // add them to the list toOpenTab.add(pr); } else { mainFrame.addParserResult(pr, first); first = false; } } // finally add things to the currently opened tab for (ParserResult pr : toOpenTab) { mainFrame.addParserResult(pr, first); first = false; } for (ParserResult pr : failed) { String message = Localization.lang("Error opening file '%0'.", pr.getPath().map(Path::toString).orElse("(File name unknown)")) + "\n" + pr.getErrorMessage(); mainFrame.getDialogService().showErrorDialogAndWait(Localization.lang("Error opening file"), message); } // Display warnings, if any int tabNumber = 0; for (ParserResult pr : bibDatabases) { ParserResultWarningDialog.showParserResultWarningDialog(pr, mainFrame, tabNumber++); } // After adding the databases, go through each and see if // any post open actions need to be done. For instance, checking // if we found new entry types that can be imported, or checking // if the database contents should be modified due to new features // in this version of JabRef. // Note that we have to check whether i does not go over getBasePanelCount(). // This is because importToOpen might have been used, which adds to // loadedDatabases, but not to getBasePanelCount() for (int i = 0; (i < bibDatabases.size()) && (i < mainFrame.getBasePanelCount()); i++) { ParserResult pr = bibDatabases.get(i); LibraryTab libraryTab = mainFrame.getLibraryTabAt(i); OpenDatabaseAction.performPostOpenActions(libraryTab, pr); } LOGGER.debug("Finished adding panels"); } private void saveWindowState(Stage mainStage) { GuiPreferences preferences = preferencesService.getGuiPreferences(); preferences.setPositionX(mainStage.getX()); preferences.setPositionY(mainStage.getY()); preferences.setSizeX(mainStage.getWidth()); preferences.setSizeY(mainStage.getHeight()); preferences.setWindowMaximised(mainStage.isMaximized()); debugLogWindowState(mainStage); } /** * outprints the Data from the Screen (only in debug mode) * * @param mainStage JabRefs stage */ private void debugLogWindowState(Stage mainStage) { if (LOGGER.isDebugEnabled()) { String debugLogString = "SCREEN DATA:" + "mainStage.WINDOW_MAXIMISED: " + mainStage.isMaximized() + "\n" + "mainStage.POS_X: " + mainStage.getX() + "\n" + "mainStage.POS_Y: " + mainStage.getY() + "\n" + "mainStage.SIZE_X: " + mainStage.getWidth() + "\n" + "mainStages.SIZE_Y: " + mainStage.getHeight() + "\n"; LOGGER.debug(debugLogString); } } /** * Tests if the window coordinates are out of the mainscreen * * @return outbounds */ private boolean isWindowPositionOutOfBounds() { return !Screen.getPrimary().getBounds().contains( preferencesService.getGuiPreferences().getPositionX(), preferencesService.getGuiPreferences().getPositionY()); } private void openLastEditedDatabases() { List<String> lastFiles = preferencesService.getGuiPreferences().getLastFilesOpened(); if (lastFiles.isEmpty()) { return; } List<Path> filesToOpen = lastFiles.stream().map(Path::of).collect(Collectors.toList()); getMainFrame().getOpenDatabaseAction().openFiles(filesToOpen); } public static JabRefFrame getMainFrame() { return mainFrame; } }
13,170
40.288401
123
java
null
jabref-main/src/main/java/org/jabref/gui/LibraryTab.java
package org.jabref.gui; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Random; import javafx.animation.PauseTransition; import javafx.application.Platform; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.collections.ListChangeListener; import javafx.geometry.Orientation; import javafx.scene.Node; import javafx.scene.control.ProgressIndicator; import javafx.scene.control.SplitPane; import javafx.scene.control.Tab; import javafx.scene.control.Tooltip; import javafx.scene.layout.BorderPane; import javafx.util.Duration; import org.jabref.gui.autocompleter.AutoCompletePreferences; import org.jabref.gui.autocompleter.PersonNameSuggestionProvider; import org.jabref.gui.autocompleter.SuggestionProviders; import org.jabref.gui.collab.DatabaseChangeMonitor; import org.jabref.gui.dialogs.AutosaveUiManager; import org.jabref.gui.entryeditor.EntryEditor; import org.jabref.gui.importer.actions.OpenDatabaseAction; import org.jabref.gui.maintable.MainTable; import org.jabref.gui.maintable.MainTableDataModel; import org.jabref.gui.undo.CountingUndoManager; import org.jabref.gui.undo.NamedCompound; import org.jabref.gui.undo.UndoableFieldChange; import org.jabref.gui.undo.UndoableInsertEntries; import org.jabref.gui.undo.UndoableRemoveEntries; import org.jabref.gui.util.BackgroundTask; import org.jabref.gui.util.DefaultTaskExecutor; import org.jabref.logic.autosaveandbackup.AutosaveManager; import org.jabref.logic.autosaveandbackup.BackupManager; import org.jabref.logic.citationstyle.CitationStyleCache; import org.jabref.logic.importer.ParserResult; import org.jabref.logic.importer.util.FileFieldParser; import org.jabref.logic.l10n.Localization; import org.jabref.logic.pdf.FileAnnotationCache; import org.jabref.logic.pdf.search.indexing.IndexingTaskManager; import org.jabref.logic.pdf.search.indexing.PdfIndexer; import org.jabref.logic.search.SearchQuery; import org.jabref.logic.shared.DatabaseLocation; import org.jabref.logic.util.UpdateField; import org.jabref.logic.util.io.FileUtil; import org.jabref.model.FieldChange; import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.database.event.BibDatabaseContextChangedEvent; import org.jabref.model.database.event.EntriesAddedEvent; import org.jabref.model.database.event.EntriesRemovedEvent; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.LinkedFile; import org.jabref.model.entry.event.EntriesEventSource; import org.jabref.model.entry.event.EntryChangedEvent; import org.jabref.model.entry.event.FieldChangedEvent; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldFactory; import org.jabref.model.entry.field.StandardField; import org.jabref.model.util.FileUpdateMonitor; import org.jabref.preferences.PreferencesService; import com.google.common.eventbus.Subscribe; import com.tobiasdiez.easybind.EasyBind; import com.tobiasdiez.easybind.Subscription; import org.controlsfx.control.NotificationPane; import org.controlsfx.control.action.Action; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LibraryTab extends Tab { private static final Logger LOGGER = LoggerFactory.getLogger(LibraryTab.class); private final JabRefFrame frame; private final CountingUndoManager undoManager; private final DialogService dialogService; private final PreferencesService preferencesService; private final FileUpdateMonitor fileUpdateMonitor; private final StateManager stateManager; private final BooleanProperty changedProperty = new SimpleBooleanProperty(false); private final BooleanProperty nonUndoableChangeProperty = new SimpleBooleanProperty(false); private BibDatabaseContext bibDatabaseContext; private MainTableDataModel tableModel; private CitationStyleCache citationStyleCache; private FileAnnotationCache annotationCache; private EntryEditor entryEditor; private MainTable mainTable; private BasePanelMode mode = BasePanelMode.SHOWING_NOTHING; private SplitPane splitPane; private DatabaseNotification databaseNotificationPane; private boolean saving; private PersonNameSuggestionProvider searchAutoCompleter; // Used to track whether the base has changed since last save. private BibEntry showing; private SuggestionProviders suggestionProviders; @SuppressWarnings({"FieldCanBeLocal"}) private Subscription dividerPositionSubscription; // the query the user searches when this BasePanel is active private Optional<SearchQuery> currentSearchQuery = Optional.empty(); private Optional<DatabaseChangeMonitor> changeMonitor = Optional.empty(); private BackgroundTask<ParserResult> dataLoadingTask; private final IndexingTaskManager indexingTaskManager = new IndexingTaskManager(Globals.TASK_EXECUTOR); public LibraryTab(BibDatabaseContext bibDatabaseContext, JabRefFrame frame, PreferencesService preferencesService, StateManager stateManager, FileUpdateMonitor fileUpdateMonitor) { this.frame = Objects.requireNonNull(frame); this.bibDatabaseContext = Objects.requireNonNull(bibDatabaseContext); this.undoManager = frame.getUndoManager(); this.dialogService = frame.getDialogService(); this.preferencesService = Objects.requireNonNull(preferencesService); this.stateManager = Objects.requireNonNull(stateManager); this.fileUpdateMonitor = fileUpdateMonitor; bibDatabaseContext.getDatabase().registerListener(this); bibDatabaseContext.getMetaData().registerListener(this); this.tableModel = new MainTableDataModel(getBibDatabaseContext(), preferencesService, stateManager); citationStyleCache = new CitationStyleCache(bibDatabaseContext); annotationCache = new FileAnnotationCache(bibDatabaseContext, preferencesService.getFilePreferences()); setupMainPanel(); setupAutoCompletion(); this.getDatabase().registerListener(new SearchListener()); this.getDatabase().registerListener(new IndexUpdateListener()); this.getDatabase().registerListener(new EntriesRemovedListener()); // ensure that at each addition of a new entry, the entry is added to the groups interface this.bibDatabaseContext.getDatabase().registerListener(new GroupTreeListener()); // ensure that all entry changes mark the panel as changed this.bibDatabaseContext.getDatabase().registerListener(this); this.getDatabase().registerListener(new UpdateTimestampListener(preferencesService)); this.entryEditor = new EntryEditor(this); // set LibraryTab ID for drag'n'drop // ID content doesn't matter, we only need different tabs to have different ID this.setId(Long.valueOf(new Random().nextLong()).toString()); Platform.runLater(() -> { EasyBind.subscribe(changedProperty, this::updateTabTitle); stateManager.getOpenDatabases().addListener((ListChangeListener<BibDatabaseContext>) c -> updateTabTitle(changedProperty.getValue())); }); } private static void addChangedInformation(StringBuilder text, String fileName) { text.append("\n"); text.append(Localization.lang("Library '%0' has changed.", fileName)); } private static void addModeInfo(StringBuilder text, BibDatabaseContext bibDatabaseContext) { String mode = bibDatabaseContext.getMode().getFormattedName(); String modeInfo = String.format("\n%s", Localization.lang("%0 mode", mode)); text.append(modeInfo); } private static void addSharedDbInformation(StringBuilder text, BibDatabaseContext bibDatabaseContext) { text.append(bibDatabaseContext.getDBMSSynchronizer().getDBName()); text.append(" ["); text.append(Localization.lang("shared")); text.append("]"); } public void setDataLoadingTask(BackgroundTask<ParserResult> dataLoadingTask) { this.dataLoadingTask = dataLoadingTask; } public void cancelLoading() { if (dataLoadingTask != null) { dataLoadingTask.cancel(); } } /** * The layout to display in the tab when it's loading */ public Node createLoadingAnimationLayout() { ProgressIndicator progressIndicator = new ProgressIndicator(ProgressIndicator.INDETERMINATE_PROGRESS); BorderPane pane = new BorderPane(); pane.setCenter(progressIndicator); return pane; } public void onDatabaseLoadingStarted() { Node loadingLayout = createLoadingAnimationLayout(); getMainTable().placeholderProperty().setValue(loadingLayout); frame.addTab(this, true); } public void onDatabaseLoadingSucceed(ParserResult result) { BibDatabaseContext context = result.getDatabaseContext(); OpenDatabaseAction.performPostOpenActions(this, result); feedData(context); if (preferencesService.getFilePreferences().shouldFulltextIndexLinkedFiles()) { try { indexingTaskManager.updateIndex(PdfIndexer.of(bibDatabaseContext, preferencesService.getFilePreferences()), bibDatabaseContext); } catch (IOException e) { LOGGER.error("Cannot access lucene index", e); } } } public void onDatabaseLoadingFailed(Exception ex) { String title = Localization.lang("Connection error"); String content = String.format("%s\n\n%s", ex.getMessage(), Localization.lang("A local copy will be opened.")); dialogService.showErrorDialogAndWait(title, content, ex); } public void feedData(BibDatabaseContext bibDatabaseContextFromParserResult) { cleanUp(); if (this.getTabPane().getSelectionModel().selectedItemProperty().get().equals(this)) { // If you open an existing library, a library tab with a loading animation is added immediately. // At that point, the library tab is given a temporary bibDatabaseContext with no entries. // This line is necessary because, while there is already a binding that updates the active database when a new tab is added, // it doesn't handle the case when a library is loaded asynchronously. // See org.jabref.gui.LibraryTab.createLibraryTab for the asynchronous loading. stateManager.setActiveDatabase(bibDatabaseContextFromParserResult); } // Remove existing dummy BibDatabaseContext and add correct BibDatabaseContext from ParserResult to trigger changes in the openDatabases list in the stateManager Optional<BibDatabaseContext> foundExistingBibDatabase = stateManager.getOpenDatabases().stream().filter(databaseContext -> databaseContext.equals(this.bibDatabaseContext)).findFirst(); foundExistingBibDatabase.ifPresent(databaseContext -> stateManager.getOpenDatabases().remove(databaseContext)); this.bibDatabaseContext = Objects.requireNonNull(bibDatabaseContextFromParserResult); stateManager.getOpenDatabases().add(bibDatabaseContextFromParserResult); bibDatabaseContextFromParserResult.getDatabase().registerListener(this); bibDatabaseContextFromParserResult.getMetaData().registerListener(this); this.tableModel = new MainTableDataModel(getBibDatabaseContext(), preferencesService, stateManager); citationStyleCache = new CitationStyleCache(bibDatabaseContextFromParserResult); annotationCache = new FileAnnotationCache(bibDatabaseContextFromParserResult, preferencesService.getFilePreferences()); setupMainPanel(); setupAutoCompletion(); this.getDatabase().registerListener(new SearchListener()); this.getDatabase().registerListener(new EntriesRemovedListener()); // ensure that at each addition of a new entry, the entry is added to the groups interface this.bibDatabaseContext.getDatabase().registerListener(new GroupTreeListener()); // ensure that all entry changes mark the panel as changed this.bibDatabaseContext.getDatabase().registerListener(this); this.getDatabase().registerListener(new UpdateTimestampListener(preferencesService)); this.entryEditor = new EntryEditor(this); Platform.runLater(() -> { EasyBind.subscribe(changedProperty, this::updateTabTitle); stateManager.getOpenDatabases().addListener((ListChangeListener<BibDatabaseContext>) c -> updateTabTitle(changedProperty.getValue())); }); installAutosaveManagerAndBackupManager(); } public void installAutosaveManagerAndBackupManager() { if (isDatabaseReadyForAutoSave(bibDatabaseContext)) { AutosaveManager autosaveManager = AutosaveManager.start(bibDatabaseContext); autosaveManager.registerListener(new AutosaveUiManager(this)); } if (isDatabaseReadyForBackup(bibDatabaseContext) && preferencesService.getFilePreferences().shouldCreateBackup()) { BackupManager.start(bibDatabaseContext, Globals.entryTypesManager, preferencesService); } } private boolean isDatabaseReadyForAutoSave(BibDatabaseContext context) { return ((context.getLocation() == DatabaseLocation.SHARED) || ((context.getLocation() == DatabaseLocation.LOCAL) && preferencesService.getLibraryPreferences().shouldAutoSave())) && context.getDatabasePath().isPresent(); } private boolean isDatabaseReadyForBackup(BibDatabaseContext context) { return (context.getLocation() == DatabaseLocation.LOCAL) && context.getDatabasePath().isPresent(); } /** * Sets the title of the tab modification-asterisk filename – path-fragment * <p> * The modification-asterisk (*) is shown if the file was modified since last save (path-fragment is only shown if filename is not (globally) unique) * <p> * Example: *jabref-authors.bib – testbib */ public void updateTabTitle(boolean isChanged) { boolean isAutosaveEnabled = preferencesService.getLibraryPreferences().shouldAutoSave(); DatabaseLocation databaseLocation = bibDatabaseContext.getLocation(); Optional<Path> file = bibDatabaseContext.getDatabasePath(); StringBuilder tabTitle = new StringBuilder(); StringBuilder toolTipText = new StringBuilder(); if (file.isPresent()) { // Modification asterisk if (isChanged && !isAutosaveEnabled) { tabTitle.append('*'); } // Filename Path databasePath = file.get(); String fileName = databasePath.getFileName().toString(); tabTitle.append(fileName); toolTipText.append(databasePath.toAbsolutePath().toString()); if (databaseLocation == DatabaseLocation.SHARED) { tabTitle.append(" \u2013 "); addSharedDbInformation(tabTitle, bibDatabaseContext); toolTipText.append(' '); addSharedDbInformation(toolTipText, bibDatabaseContext); } // Database mode addModeInfo(toolTipText, bibDatabaseContext); // Changed information (tooltip) if (isChanged && !isAutosaveEnabled) { addChangedInformation(toolTipText, fileName); } // Unique path fragment Optional<String> uniquePathPart = FileUtil.getUniquePathDirectory(stateManager.collectAllDatabasePaths(), databasePath); uniquePathPart.ifPresent(part -> tabTitle.append(" \u2013 ").append(part)); } else { if (databaseLocation == DatabaseLocation.LOCAL) { tabTitle.append(Localization.lang("untitled")); if (bibDatabaseContext.getDatabase().hasEntries()) { // if the database is not empty and no file is assigned, // the database came from an import and has to be treated somehow // -> mark as changed tabTitle.append('*'); } } else { addSharedDbInformation(tabTitle, bibDatabaseContext); addSharedDbInformation(toolTipText, bibDatabaseContext); } addModeInfo(toolTipText, bibDatabaseContext); if ((databaseLocation == DatabaseLocation.LOCAL) && bibDatabaseContext.getDatabase().hasEntries()) { addChangedInformation(toolTipText, Localization.lang("untitled")); } } DefaultTaskExecutor.runInJavaFXThread(() -> { textProperty().setValue(tabTitle.toString()); setTooltip(new Tooltip(toolTipText.toString())); }); if (preferencesService.getFilePreferences().shouldFulltextIndexLinkedFiles()) { indexingTaskManager.updateDatabaseName(tabTitle.toString()); } } @Subscribe public void listen(BibDatabaseContextChangedEvent event) { this.changedProperty.setValue(true); } /** * Returns a collection of suggestion providers, which are populated from the current library. */ public SuggestionProviders getSuggestionProviders() { return suggestionProviders; } public BasePanelMode getMode() { return mode; } public void setMode(BasePanelMode mode) { this.mode = mode; } public JabRefFrame frame() { return frame; } /** * Removes the selected entries from the database * * @param cut If false the user will get asked if he really wants to delete the entries, and it will be localized as "deleted". If true the action will be localized as "cut" */ public void delete(boolean cut) { delete(cut, mainTable.getSelectedEntries()); } /** * Removes the selected entries from the database * * @param cut If false the user will get asked if he really wants to delete the entries, and it will be localized as "deleted". If true the action will be localized as "cut" */ private void delete(boolean cut, List<BibEntry> entries) { if (entries.isEmpty()) { return; } if (!cut && !showDeleteConfirmationDialog(entries.size())) { return; } getUndoManager().addEdit(new UndoableRemoveEntries(bibDatabaseContext.getDatabase(), entries, cut)); bibDatabaseContext.getDatabase().removeEntries(entries); ensureNotShowingBottomPanel(entries); this.changedProperty.setValue(true); dialogService.notify(formatOutputMessage(cut ? Localization.lang("Cut") : Localization.lang("Deleted"), entries.size())); // prevent the main table from loosing focus mainTable.requestFocus(); } public void delete(BibEntry entry) { delete(false, Collections.singletonList(entry)); } public void registerUndoableChanges(List<FieldChange> changes) { NamedCompound ce = new NamedCompound(Localization.lang("Save actions")); for (FieldChange change : changes) { ce.addEdit(new UndoableFieldChange(change)); } ce.end(); if (ce.hasEdits()) { getUndoManager().addEdit(ce); } } public void insertEntry(final BibEntry bibEntry) { if (bibEntry != null) { insertEntries(Collections.singletonList(bibEntry)); } } /** * This method is called from JabRefFrame when the user wants to create a new entry or entries. It is necessary when the user would expect the added entry or one of the added entries to be selected in the entry editor * * @param entries The new entries. */ public void insertEntries(final List<BibEntry> entries) { if (!entries.isEmpty()) { bibDatabaseContext.getDatabase().insertEntries(entries); // Set owner and timestamp UpdateField.setAutomaticFields(entries, preferencesService.getOwnerPreferences(), preferencesService.getTimestampPreferences()); // Create an UndoableInsertEntries object. getUndoManager().addEdit(new UndoableInsertEntries(bibDatabaseContext.getDatabase(), entries)); this.changedProperty.setValue(true); // The database just changed. if (preferencesService.getEntryEditorPreferences().shouldOpenOnNewEntry()) { showAndEdit(entries.get(0)); } clearAndSelect(entries.get(0)); } } public void editEntryAndFocusField(BibEntry entry, Field field) { showAndEdit(entry); Platform.runLater(() -> { // Focus field and entry in main table (async to give entry editor time to load) entryEditor.setFocusToField(field); clearAndSelect(entry); }); } private void createMainTable() { mainTable = new MainTable(tableModel, this, bibDatabaseContext, preferencesService, dialogService, stateManager, Globals.getKeyPrefs(), Globals.getClipboardManager(), Globals.TASK_EXECUTOR, fileUpdateMonitor); // Add the listener that binds selection to state manager (TODO: should be replaced by proper JavaFX binding as soon as table is implemented in JavaFX) mainTable.addSelectionListener(listEvent -> stateManager.setSelectedEntries(mainTable.getSelectedEntries())); // Update entry editor and preview according to selected entries mainTable.addSelectionListener(event -> mainTable.getSelectedEntries() .stream() .findFirst() .ifPresent(entryEditor::setEntry)); } public void setupMainPanel() { splitPane = new SplitPane(); splitPane.setOrientation(Orientation.VERTICAL); createMainTable(); splitPane.getItems().add(mainTable); databaseNotificationPane = new DatabaseNotification(splitPane); setContent(databaseNotificationPane); // Saves the divider position as soon as it changes // We need to keep a reference to the subscription, otherwise the binding gets garbage collected dividerPositionSubscription = EasyBind.valueAt(splitPane.getDividers(), 0) .mapObservable(SplitPane.Divider::positionProperty) .subscribeToValues(this::saveDividerLocation); // Add changePane in case a file is present - otherwise just add the splitPane to the panel Optional<Path> file = bibDatabaseContext.getDatabasePath(); if (file.isPresent()) { resetChangeMonitor(); } else { if (bibDatabaseContext.getDatabase().hasEntries()) { // if the database is not empty and no file is assigned, // the database came from an import and has to be treated somehow // -> mark as changed this.changedProperty.setValue(true); } } } /** * Set up auto completion for this database */ private void setupAutoCompletion() { AutoCompletePreferences autoCompletePreferences = preferencesService.getAutoCompletePreferences(); if (autoCompletePreferences.shouldAutoComplete()) { suggestionProviders = new SuggestionProviders(getDatabase(), Globals.journalAbbreviationRepository, autoCompletePreferences); } else { // Create empty suggestion providers if auto completion is deactivated suggestionProviders = new SuggestionProviders(); } searchAutoCompleter = new PersonNameSuggestionProvider(FieldFactory.getPersonNameFields(), getDatabase()); } public void updateSearchManager() { frame.getGlobalSearchBar().setAutoCompleter(searchAutoCompleter); } public EntryEditor getEntryEditor() { return entryEditor; } /** * Sets the entry editor as the bottom component in the split pane. If an entry editor already was shown, makes sure that the divider doesn't move. Updates the mode to SHOWING_EDITOR. Then shows the given entry. * * @param entry The entry to edit. */ public void showAndEdit(BibEntry entry) { showBottomPane(BasePanelMode.SHOWING_EDITOR); // We use != instead of equals because of performance reasons if (entry != getShowing()) { entryEditor.setEntry(entry); showing = entry; } entryEditor.requestFocus(); } private void showBottomPane(BasePanelMode newMode) { if (newMode != BasePanelMode.SHOWING_EDITOR) { throw new UnsupportedOperationException("new mode not recognized: " + newMode.name()); } Node pane = entryEditor; if (splitPane.getItems().size() == 2) { splitPane.getItems().set(1, pane); } else { splitPane.getItems().add(1, pane); } mode = newMode; splitPane.setDividerPositions(preferencesService.getEntryEditorPreferences().getDividerPosition()); } /** * Removes the bottom component. */ public void closeBottomPane() { mode = BasePanelMode.SHOWING_NOTHING; splitPane.getItems().remove(entryEditor); } /** * This method selects the given entry, and scrolls it into view in the table. If an entryEditor is shown, it is given focus afterwards. */ public void clearAndSelect(final BibEntry bibEntry) { mainTable.clearAndSelect(bibEntry); } public void selectPreviousEntry() { mainTable.getSelectionModel().clearAndSelect(mainTable.getSelectionModel().getSelectedIndex() - 1); } public void selectNextEntry() { mainTable.getSelectionModel().clearAndSelect(mainTable.getSelectionModel().getSelectedIndex() + 1); } /** * This method is called from an EntryEditor when it should be closed. We relay to the selection listener, which takes care of the rest. */ public void entryEditorClosing() { closeBottomPane(); mainTable.requestFocus(); } /** * Closes the entry editor if it is showing any of the given entries. */ private void ensureNotShowingBottomPanel(List<BibEntry> entriesToCheck) { // This method is not able to close the bottom pane currently if ((mode == BasePanelMode.SHOWING_EDITOR) && (entriesToCheck.contains(entryEditor.getEntry()))) { closeBottomPane(); } } public void updateEntryEditorIfShowing() { if (mode == BasePanelMode.SHOWING_EDITOR) { BibEntry currentEntry = entryEditor.getEntry(); showAndEdit(currentEntry); } } /** * Put an asterisk behind the filename to indicate the database has changed. */ public synchronized void markChangedOrUnChanged() { if (getUndoManager().hasChanged()) { this.changedProperty.setValue(true); } else if (changedProperty.getValue() && !nonUndoableChangeProperty.getValue()) { this.changedProperty.setValue(false); } } public BibDatabase getDatabase() { return bibDatabaseContext.getDatabase(); } private boolean showDeleteConfirmationDialog(int numberOfEntries) { if (preferencesService.getWorkspacePreferences().shouldConfirmDelete()) { String title = Localization.lang("Delete entry"); String message = Localization.lang("Really delete the selected entry?"); String okButton = Localization.lang("Delete entry"); String cancelButton = Localization.lang("Keep entry"); if (numberOfEntries > 1) { title = Localization.lang("Delete multiple entries"); message = Localization.lang("Really delete the %0 selected entries?", Integer.toString(numberOfEntries)); okButton = Localization.lang("Delete entries"); cancelButton = Localization.lang("Keep entries"); } return dialogService.showConfirmationDialogWithOptOutAndWait(title, message, okButton, cancelButton, Localization.lang("Do not ask again"), optOut -> preferencesService.getWorkspacePreferences().setConfirmDelete(!optOut)); } else { return true; } } /** * Depending on whether a preview or an entry editor is showing, save the current divider location in the correct preference setting. */ private void saveDividerLocation(Number position) { if (mode == BasePanelMode.SHOWING_EDITOR) { preferencesService.getEntryEditorPreferences().setDividerPosition(position.doubleValue()); } } /** * Perform necessary cleanup when this BasePanel is closed. */ public void cleanUp() { changeMonitor.ifPresent(DatabaseChangeMonitor::unregister); AutosaveManager.shutdown(bibDatabaseContext); BackupManager.shutdown(bibDatabaseContext, preferencesService.getFilePreferences().getBackupDirectory(), preferencesService.getFilePreferences().shouldCreateBackup()); } /** * Get an array containing the currently selected entries. The array is stable and not changed if the selection changes * * @return A list containing the selected entries. Is never null. */ public List<BibEntry> getSelectedEntries() { return mainTable.getSelectedEntries(); } public BibDatabaseContext getBibDatabaseContext() { return this.bibDatabaseContext; } public boolean isSaving() { return saving; } public void setSaving(boolean saving) { this.saving = saving; } private BibEntry getShowing() { return showing; } public String formatOutputMessage(String start, int count) { return String.format("%s %d %s.", start, count, (count > 1 ? Localization.lang("entries") : Localization.lang("entry"))); } public CountingUndoManager getUndoManager() { return undoManager; } public MainTable getMainTable() { return mainTable; } public Optional<SearchQuery> getCurrentSearchQuery() { return currentSearchQuery; } /** * Set the query the user currently searches while this basepanel is active */ public void setCurrentSearchQuery(Optional<SearchQuery> currentSearchQuery) { this.currentSearchQuery = currentSearchQuery; } public CitationStyleCache getCitationStyleCache() { return citationStyleCache; } public FileAnnotationCache getAnnotationCache() { return annotationCache; } public void resetChangeMonitor() { changeMonitor.ifPresent(DatabaseChangeMonitor::unregister); changeMonitor = Optional.of(new DatabaseChangeMonitor(bibDatabaseContext, fileUpdateMonitor, Globals.TASK_EXECUTOR, dialogService, preferencesService, databaseNotificationPane)); } public void copy() { mainTable.copy(); } public void paste() { mainTable.paste(); } public void dropEntry(List<BibEntry> entriesToAdd) { mainTable.dropEntry(entriesToAdd); } public void cut() { mainTable.cut(); } public BooleanProperty changedProperty() { return changedProperty; } public boolean isModified() { return changedProperty.getValue(); } public void markBaseChanged() { this.changedProperty.setValue(true); } public BooleanProperty nonUndoableChangeProperty() { return nonUndoableChangeProperty; } public void markNonUndoableBaseChanged() { this.nonUndoableChangeProperty.setValue(true); this.changedProperty.setValue(true); } public void resetChangedProperties() { this.nonUndoableChangeProperty.setValue(false); this.changedProperty.setValue(false); } /** * Creates a new library tab. Contents are loaded by the {@code dataLoadingTask}. Most of the other parameters are required by {@code resetChangeMonitor()}. * * @param dataLoadingTask The task to execute to load the data. It is executed using {@link org.jabref.gui.Globals.TASK_EXECUTOR}. * @param file the path to the file (loaded by the dataLoadingTask) */ public static LibraryTab createLibraryTab(BackgroundTask<ParserResult> dataLoadingTask, Path file, PreferencesService preferencesService, StateManager stateManager, JabRefFrame frame, FileUpdateMonitor fileUpdateMonitor) { BibDatabaseContext context = new BibDatabaseContext(); context.setDatabasePath(file); LibraryTab newTab = new LibraryTab(context, frame, preferencesService, stateManager, fileUpdateMonitor); newTab.setDataLoadingTask(dataLoadingTask); dataLoadingTask.onRunning(newTab::onDatabaseLoadingStarted) .onSuccess(newTab::onDatabaseLoadingSucceed) .onFailure(newTab::onDatabaseLoadingFailed) .executeWith(Globals.TASK_EXECUTOR); return newTab; } private class GroupTreeListener { @Subscribe public void listen(EntriesAddedEvent addedEntriesEvent) { // if the event is an undo, don't add it to the current group if (addedEntriesEvent.getEntriesEventSource() == EntriesEventSource.UNDO) { return; } // Automatically add new entries to the selected group (or set of groups) if (preferencesService.getGroupsPreferences().shouldAutoAssignGroup()) { stateManager.getSelectedGroup(bibDatabaseContext).forEach( selectedGroup -> selectedGroup.addEntriesToGroup(addedEntriesEvent.getBibEntries())); } } } private class EntriesRemovedListener { @Subscribe public void listen(EntriesRemovedEvent entriesRemovedEvent) { ensureNotShowingBottomPanel(entriesRemovedEvent.getBibEntries()); } } /** * Ensures that the results of the current search are updated when a new entry is inserted into the database Actual methods for performing search must run in javafx thread */ private class SearchListener { @Subscribe public void listen(EntriesAddedEvent addedEntryEvent) { DefaultTaskExecutor.runInJavaFXThread(() -> frame.getGlobalSearchBar().performSearch()); } @Subscribe public void listen(EntryChangedEvent entryChangedEvent) { DefaultTaskExecutor.runInJavaFXThread(() -> frame.getGlobalSearchBar().performSearch()); } @Subscribe public void listen(EntriesRemovedEvent removedEntriesEvent) { // IMO only used to update the status (found X entries) DefaultTaskExecutor.runInJavaFXThread(() -> frame.getGlobalSearchBar().performSearch()); } } private class IndexUpdateListener { @Subscribe public void listen(EntriesAddedEvent addedEntryEvent) { if (preferencesService.getFilePreferences().shouldFulltextIndexLinkedFiles()) { try { PdfIndexer pdfIndexer = PdfIndexer.of(bibDatabaseContext, preferencesService.getFilePreferences()); for (BibEntry addedEntry : addedEntryEvent.getBibEntries()) { indexingTaskManager.addToIndex(pdfIndexer, addedEntry, bibDatabaseContext); } } catch (IOException e) { LOGGER.error("Cannot access lucene index", e); } } } @Subscribe public void listen(EntriesRemovedEvent removedEntriesEvent) { if (preferencesService.getFilePreferences().shouldFulltextIndexLinkedFiles()) { try { PdfIndexer pdfIndexer = PdfIndexer.of(bibDatabaseContext, preferencesService.getFilePreferences()); for (BibEntry removedEntry : removedEntriesEvent.getBibEntries()) { indexingTaskManager.removeFromIndex(pdfIndexer, removedEntry); } } catch (IOException e) { LOGGER.error("Cannot access lucene index", e); } } } @Subscribe public void listen(FieldChangedEvent fieldChangedEvent) { if (preferencesService.getFilePreferences().shouldFulltextIndexLinkedFiles()) { if (fieldChangedEvent.getField().equals(StandardField.FILE)) { List<LinkedFile> oldFileList = FileFieldParser.parse(fieldChangedEvent.getOldValue()); List<LinkedFile> newFileList = FileFieldParser.parse(fieldChangedEvent.getNewValue()); List<LinkedFile> addedFiles = new ArrayList<>(newFileList); addedFiles.remove(oldFileList); List<LinkedFile> removedFiles = new ArrayList<>(oldFileList); removedFiles.remove(newFileList); try { indexingTaskManager.addToIndex(PdfIndexer.of(bibDatabaseContext, preferencesService.getFilePreferences()), fieldChangedEvent.getBibEntry(), addedFiles, bibDatabaseContext); indexingTaskManager.removeFromIndex(PdfIndexer.of(bibDatabaseContext, preferencesService.getFilePreferences()), fieldChangedEvent.getBibEntry(), removedFiles); } catch (IOException e) { LOGGER.warn("I/O error when writing lucene index", e); } } } } } public IndexingTaskManager getIndexingTaskManager() { return indexingTaskManager; } public static class DatabaseNotification extends NotificationPane { public DatabaseNotification(Node content) { super(content); } public void notify(Node graphic, String text, List<Action> actions, Duration duration) { this.setGraphic(graphic); this.setText(text); this.getActions().setAll(actions); this.show(); if ((duration != null) && !duration.equals(Duration.ZERO)) { PauseTransition delay = new PauseTransition(duration); delay.setOnFinished(e -> this.hide()); delay.play(); } } } public DatabaseNotification getNotificationPane() { return databaseNotificationPane; } }
39,612
39.922521
221
java
null
jabref-main/src/main/java/org/jabref/gui/MainApplication.java
package org.jabref.gui; import java.util.List; import javafx.application.Application; import javafx.stage.Stage; import org.jabref.gui.openoffice.OOBibBaseConnect; import org.jabref.logic.importer.ParserResult; import org.jabref.model.util.FileUpdateMonitor; import org.jabref.preferences.JabRefPreferences; /** * JabRef's main class to process command line options and to start the UI */ public class MainApplication extends Application { private static List<ParserResult> parserResults; private static boolean isBlank; private static JabRefPreferences preferences; private static FileUpdateMonitor fileUpdateMonitor; public static void main(List<ParserResult> parserResults, boolean blank, JabRefPreferences preferences, FileUpdateMonitor fileUpdateMonitor, String[] args) { MainApplication.parserResults = parserResults; MainApplication.isBlank = blank; MainApplication.preferences = preferences; MainApplication.fileUpdateMonitor = fileUpdateMonitor; launch(args); } @Override public void start(Stage mainStage) { FallbackExceptionHandler.installExceptionHandler(); Globals.startBackgroundTasks(); new JabRefGUI(mainStage, parserResults, isBlank, preferences, fileUpdateMonitor); } @Override public void stop() { OOBibBaseConnect.closeOfficeConnection(); Globals.stopBackgroundTasks(); Globals.shutdownThreadPools(); } }
1,582
31.979167
89
java
null
jabref-main/src/main/java/org/jabref/gui/OpenConsoleAction.java
package org.jabref.gui; import java.io.IOException; import java.util.Optional; import java.util.function.Supplier; import org.jabref.gui.actions.ActionHelper; import org.jabref.gui.actions.SimpleCommand; import org.jabref.gui.desktop.JabRefDesktop; import org.jabref.model.database.BibDatabaseContext; import org.jabref.preferences.PreferencesService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class OpenConsoleAction extends SimpleCommand { private static final Logger LOGGER = LoggerFactory.getLogger(OpenConsoleAction.class); private final Supplier<BibDatabaseContext> databaseContext; private final StateManager stateManager; private final PreferencesService preferencesService; private final DialogService dialogService; /** * Creates a command that opens the console at the path of the supplied database, * or defaults to the active database. Use * {@link #OpenConsoleAction(StateManager, PreferencesService)} if not supplying * another database. */ public OpenConsoleAction(Supplier<BibDatabaseContext> databaseContext, StateManager stateManager, PreferencesService preferencesService, DialogService dialogService) { this.databaseContext = databaseContext; this.stateManager = stateManager; this.preferencesService = preferencesService; this.dialogService = dialogService; this.executable.bind(ActionHelper.needsDatabase(stateManager)); } /** * Using this constructor will result in executing the command on the active database. */ public OpenConsoleAction(StateManager stateManager, PreferencesService preferencesService, DialogService dialogService) { this(() -> null, stateManager, preferencesService, dialogService); } @Override public void execute() { Optional.ofNullable(databaseContext.get()).or(stateManager::getActiveDatabase).flatMap(BibDatabaseContext::getDatabasePath).ifPresent(path -> { try { JabRefDesktop.openConsole(path, preferencesService, dialogService); } catch (IOException e) { LOGGER.info("Could not open console", e); } }); } }
2,214
37.859649
171
java
null
jabref-main/src/main/java/org/jabref/gui/SendAsEMailAction.java
package org.jabref.gui; import java.awt.Desktop; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import org.jabref.architecture.AllowedToUseAwt; import org.jabref.gui.actions.SimpleCommand; import org.jabref.gui.desktop.JabRefDesktop; import org.jabref.gui.util.BackgroundTask; import org.jabref.logic.l10n.Localization; import org.jabref.logic.util.io.FileUtil; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.preferences.PreferencesService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Sends the selected entry as email * <p> * It uses the mailto:-mechanism * <p> * Microsoft Outlook does not support attachments via mailto * Therefore, the folder(s), where the file(s) belonging to the entry are stored, * are opened. This feature is disabled by default and can be switched on at * preferences/external programs */ @AllowedToUseAwt("Requires AWT to send an email") public abstract class SendAsEMailAction extends SimpleCommand { private static final Logger LOGGER = LoggerFactory.getLogger(SendAsEMailAction.class); private final DialogService dialogService; private final PreferencesService preferencesService; private final StateManager stateManager; public SendAsEMailAction(DialogService dialogService, PreferencesService preferencesService, StateManager stateManager) { this.dialogService = dialogService; this.preferencesService = preferencesService; this.stateManager = stateManager; } @Override public void execute() { BackgroundTask.wrap(this::sendEmail) .onSuccess(dialogService::notify) .onFailure(e -> { String message = Localization.lang("Error creating email"); LOGGER.warn(message, e); dialogService.notify(message); }) .executeWith(Globals.TASK_EXECUTOR); } private String sendEmail() throws Exception { if (!Desktop.isDesktopSupported() || stateManager.getActiveDatabase().isEmpty()) { return Localization.lang("Error creating email"); } if (stateManager.getSelectedEntries().isEmpty()) { return Localization.lang("This operation requires one or more entries to be selected."); } List<BibEntry> entries = stateManager.getSelectedEntries(); URI uriMailTo = getUriMailTo(entries); Desktop desktop = Desktop.getDesktop(); desktop.mail(uriMailTo); return String.format("%s: %d", Localization.lang("Entries added to an email"), entries.size()); } private URI getUriMailTo(List<BibEntry> entries) throws URISyntaxException { StringBuilder mailTo = new StringBuilder(); mailTo.append(getEmailAddress()); mailTo.append("?Body=").append(getBody()); mailTo.append("&Subject=").append(getSubject()); List<String> attachments = getAttachments(entries); for (String path : attachments) { mailTo.append("&Attachment=\"").append(path); mailTo.append("\""); } return new URI("mailto", mailTo.toString(), null); } private List<String> getAttachments(List<BibEntry> entries) { // open folders is needed to indirectly support email programs, which cannot handle // the unofficial "mailto:attachment" property boolean openFolders = preferencesService.getExternalApplicationsPreferences().shouldAutoOpenEmailAttachmentsFolder(); BibDatabaseContext databaseContext = stateManager.getActiveDatabase().get(); List<Path> fileList = FileUtil.getListOfLinkedFiles(entries, databaseContext.getFileDirectories(preferencesService.getFilePreferences())); List<String> attachments = new ArrayList<>(); for (Path path : fileList) { attachments.add(path.toAbsolutePath().toString()); if (openFolders) { try { JabRefDesktop.openFolderAndSelectFile(path.toAbsolutePath(), preferencesService, dialogService); } catch (IOException e) { LOGGER.debug("Cannot open file", e); } } } return attachments; } protected abstract String getEmailAddress(); protected abstract String getSubject(); protected abstract String getBody(); }
4,586
36.598361
146
java
null
jabref-main/src/main/java/org/jabref/gui/SendAsKindleEmailAction.java
package org.jabref.gui; import org.jabref.gui.actions.ActionHelper; import org.jabref.logic.l10n.Localization; import org.jabref.preferences.PreferencesService; /** * Sends attachments for selected entries to the * configured Kindle email */ public class SendAsKindleEmailAction extends SendAsEMailAction { private final PreferencesService preferencesService; public SendAsKindleEmailAction(DialogService dialogService, PreferencesService preferencesService, StateManager stateManager) { super(dialogService, preferencesService, stateManager); this.preferencesService = preferencesService; this.executable.bind(ActionHelper.needsEntriesSelected(stateManager).and(ActionHelper.hasLinkedFileForSelectedEntries(stateManager))); } @Override protected String getEmailAddress() { return preferencesService.getExternalApplicationsPreferences().getKindleEmail(); } @Override protected String getSubject() { return Localization.lang("Send to Kindle"); } @Override protected String getBody() { return Localization.lang("Send to Kindle"); } }
1,137
31.514286
142
java
null
jabref-main/src/main/java/org/jabref/gui/SendAsStandardEmailAction.java
package org.jabref.gui; import java.io.IOException; import java.io.StringWriter; import java.util.List; import org.jabref.gui.actions.ActionHelper; import org.jabref.logic.bibtex.BibEntryWriter; import org.jabref.logic.bibtex.FieldWriter; import org.jabref.logic.exporter.BibWriter; import org.jabref.logic.util.OS; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.preferences.PreferencesService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Sends the selected entries to any specifiable email * by populating the email body */ public class SendAsStandardEmailAction extends SendAsEMailAction { private static final Logger LOGGER = LoggerFactory.getLogger(SendAsStandardEmailAction.class); private final PreferencesService preferencesService; private final StateManager stateManager; public SendAsStandardEmailAction(DialogService dialogService, PreferencesService preferencesService, StateManager stateManager) { super(dialogService, preferencesService, stateManager); this.preferencesService = preferencesService; this.stateManager = stateManager; this.executable.bind(ActionHelper.needsEntriesSelected(stateManager)); } @Override protected String getEmailAddress() { return ""; } @Override protected String getSubject() { return preferencesService.getExternalApplicationsPreferences().getEmailSubject(); } @Override protected String getBody() { List<BibEntry> entries = stateManager.getSelectedEntries(); BibDatabaseContext databaseContext = stateManager.getActiveDatabase().get(); StringWriter rawEntries = new StringWriter(); BibWriter bibWriter = new BibWriter(rawEntries, OS.NEWLINE); BibEntryWriter bibtexEntryWriter = new BibEntryWriter(new FieldWriter(preferencesService.getFieldPreferences()), Globals.entryTypesManager); for (BibEntry entry : entries) { try { bibtexEntryWriter.write(entry, bibWriter, databaseContext.getMode()); } catch (IOException e) { LOGGER.warn("Problem creating BibTeX file for mailing.", e); } } return rawEntries.toString(); } }
2,297
34.353846
148
java
null
jabref-main/src/main/java/org/jabref/gui/StateManager.java
package org.jabref.gui; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import javafx.beans.Observable; import javafx.beans.binding.Bindings; import javafx.beans.property.IntegerProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.ReadOnlyListProperty; import javafx.beans.property.ReadOnlyListWrapper; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.collections.ObservableMap; import javafx.concurrent.Task; import javafx.scene.Node; import javafx.util.Pair; import org.jabref.gui.edit.automaticfiededitor.LastAutomaticFieldEditorEdit; import org.jabref.gui.sidepane.SidePaneType; import org.jabref.gui.util.BackgroundTask; import org.jabref.gui.util.CustomLocalDragboard; import org.jabref.gui.util.DialogWindowState; import org.jabref.gui.util.OptionalObjectProperty; import org.jabref.logic.search.SearchQuery; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.groups.GroupTreeNode; import org.jabref.model.util.OptionalUtil; import com.tobiasdiez.easybind.EasyBind; import com.tobiasdiez.easybind.EasyBinding; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class manages the GUI-state of JabRef, including: * * <ul> * <li>currently selected database</li> * <li>currently selected group</li> * <li>active search</li> * <li>active number of search results</li> * <li>focus owner</li> * <li>dialog window sizes/positions</li> * </ul> */ public class StateManager { private static final Logger LOGGER = LoggerFactory.getLogger(StateManager.class); private final CustomLocalDragboard localDragboard = new CustomLocalDragboard(); private final ObservableList<BibDatabaseContext> openDatabases = FXCollections.observableArrayList(); private final OptionalObjectProperty<BibDatabaseContext> activeDatabase = OptionalObjectProperty.empty(); private final ReadOnlyListWrapper<GroupTreeNode> activeGroups = new ReadOnlyListWrapper<>(FXCollections.observableArrayList()); private final ObservableList<BibEntry> selectedEntries = FXCollections.observableArrayList(); private final ObservableMap<BibDatabaseContext, ObservableList<GroupTreeNode>> selectedGroups = FXCollections.observableHashMap(); private final OptionalObjectProperty<SearchQuery> activeSearchQuery = OptionalObjectProperty.empty(); private final ObservableMap<BibDatabaseContext, IntegerProperty> searchResultMap = FXCollections.observableHashMap(); private final OptionalObjectProperty<Node> focusOwner = OptionalObjectProperty.empty(); private final ObservableList<Pair<BackgroundTask<?>, Task<?>>> backgroundTasks = FXCollections.observableArrayList(task -> new Observable[]{task.getValue().progressProperty(), task.getValue().runningProperty()}); private final EasyBinding<Boolean> anyTaskRunning = EasyBind.reduce(backgroundTasks, tasks -> tasks.map(Pair::getValue).anyMatch(Task::isRunning)); private final EasyBinding<Boolean> anyTasksThatWillNotBeRecoveredRunning = EasyBind.reduce(backgroundTasks, tasks -> tasks.anyMatch(task -> !task.getKey().willBeRecoveredAutomatically() && task.getValue().isRunning())); private final EasyBinding<Double> tasksProgress = EasyBind.reduce(backgroundTasks, tasks -> tasks.map(Pair::getValue).filter(Task::isRunning).mapToDouble(Task::getProgress).average().orElse(1)); private final ObservableMap<String, DialogWindowState> dialogWindowStates = FXCollections.observableHashMap(); private final ObservableList<SidePaneType> visibleSidePanes = FXCollections.observableArrayList(); private final ObjectProperty<LastAutomaticFieldEditorEdit> lastAutomaticFieldEditorEdit = new SimpleObjectProperty<>(); private final ObservableList<String> searchHistory = FXCollections.observableArrayList(); public StateManager() { activeGroups.bind(Bindings.valueAt(selectedGroups, activeDatabase.orElseOpt(null))); } public ObservableList<SidePaneType> getVisibleSidePaneComponents() { return visibleSidePanes; } public CustomLocalDragboard getLocalDragboard() { return localDragboard; } public ObservableList<BibDatabaseContext> getOpenDatabases() { return openDatabases; } public OptionalObjectProperty<BibDatabaseContext> activeDatabaseProperty() { return activeDatabase; } public OptionalObjectProperty<SearchQuery> activeSearchQueryProperty() { return activeSearchQuery; } public void setActiveSearchResultSize(BibDatabaseContext database, IntegerProperty resultSize) { searchResultMap.put(database, resultSize); } public IntegerProperty getSearchResultSize() { return searchResultMap.getOrDefault(activeDatabase.getValue().orElse(new BibDatabaseContext()), new SimpleIntegerProperty(0)); } public ReadOnlyListProperty<GroupTreeNode> activeGroupProperty() { return activeGroups.getReadOnlyProperty(); } public ObservableList<BibEntry> getSelectedEntries() { return selectedEntries; } public void setSelectedEntries(List<BibEntry> newSelectedEntries) { selectedEntries.setAll(newSelectedEntries); } public void setSelectedGroups(BibDatabaseContext database, List<GroupTreeNode> newSelectedGroups) { Objects.requireNonNull(newSelectedGroups); selectedGroups.put(database, FXCollections.observableArrayList(newSelectedGroups)); } public ObservableList<GroupTreeNode> getSelectedGroup(BibDatabaseContext database) { ObservableList<GroupTreeNode> selectedGroupsForDatabase = selectedGroups.get(database); return selectedGroupsForDatabase != null ? selectedGroupsForDatabase : FXCollections.observableArrayList(); } public void clearSelectedGroups(BibDatabaseContext database) { selectedGroups.remove(database); } public Optional<BibDatabaseContext> getActiveDatabase() { return activeDatabase.get(); } public void setActiveDatabase(BibDatabaseContext database) { if (database == null) { LOGGER.info("No open database detected"); activeDatabaseProperty().set(Optional.empty()); } else { activeDatabaseProperty().set(Optional.of(database)); } } public List<BibEntry> getEntriesInCurrentDatabase() { return OptionalUtil.flatMap(activeDatabase.get(), BibDatabaseContext::getEntries) .collect(Collectors.toList()); } public void clearSearchQuery() { activeSearchQuery.setValue(Optional.empty()); } public void setSearchQuery(SearchQuery searchQuery) { activeSearchQuery.setValue(Optional.of(searchQuery)); } public OptionalObjectProperty<Node> focusOwnerProperty() { return focusOwner; } public Optional<Node> getFocusOwner() { return focusOwner.get(); } public ObservableList<Task<?>> getBackgroundTasks() { return EasyBind.map(backgroundTasks, Pair::getValue); } public void addBackgroundTask(BackgroundTask<?> backgroundTask, Task<?> task) { this.backgroundTasks.add(0, new Pair<>(backgroundTask, task)); } public EasyBinding<Boolean> getAnyTaskRunning() { return anyTaskRunning; } public EasyBinding<Boolean> getAnyTasksThatWillNotBeRecoveredRunning() { return anyTasksThatWillNotBeRecoveredRunning; } public EasyBinding<Double> getTasksProgress() { return tasksProgress; } public DialogWindowState getDialogWindowState(String className) { return dialogWindowStates.get(className); } public void setDialogWindowState(String className, DialogWindowState state) { dialogWindowStates.put(className, state); } public ObjectProperty<LastAutomaticFieldEditorEdit> lastAutomaticFieldEditorEditProperty() { return lastAutomaticFieldEditorEdit; } public LastAutomaticFieldEditorEdit getLastAutomaticFieldEditorEdit() { return lastAutomaticFieldEditorEditProperty().get(); } public void setLastAutomaticFieldEditorEdit(LastAutomaticFieldEditorEdit automaticFieldEditorEdit) { lastAutomaticFieldEditorEditProperty().set(automaticFieldEditorEdit); } public List<String> collectAllDatabasePaths() { List<String> list = new ArrayList<>(); getOpenDatabases().stream() .map(BibDatabaseContext::getDatabasePath) .forEachOrdered(pathOptional -> pathOptional.ifPresentOrElse( path -> list.add(path.toAbsolutePath().toString()), () -> list.add(""))); return list; } public void addSearchHistory(String search) { searchHistory.remove(search); searchHistory.add(search); } public ObservableList<String> getWholeSearchHistory() { return searchHistory; } public List<String> getLastSearchHistory(int size) { int sizeSearches = searchHistory.size(); if (size < sizeSearches) { return searchHistory.subList(sizeSearches - size, sizeSearches); } return searchHistory; } public void clearSearchHistory() { searchHistory.clear(); } }
9,545
38.941423
223
java
null
jabref-main/src/main/java/org/jabref/gui/UpdateTimestampListener.java
package org.jabref.gui; import org.jabref.model.entry.event.EntriesEventSource; import org.jabref.model.entry.event.EntryChangedEvent; import org.jabref.model.entry.field.StandardField; import org.jabref.preferences.PreferencesService; import com.google.common.eventbus.Subscribe; /** * Updates the timestamp of changed entries if the feature is enabled */ class UpdateTimestampListener { private final PreferencesService preferencesService; UpdateTimestampListener(PreferencesService preferencesService) { this.preferencesService = preferencesService; } @Subscribe public void listen(EntryChangedEvent event) { // The event source needs to be checked, since the timestamp is always updated on every change. The cleanup formatter is an exception to that behaviour, // since it just should move the contents from the timestamp field to modificationdate or creationdate. if (preferencesService.getTimestampPreferences().shouldAddModificationDate() && event.getEntriesEventSource() != EntriesEventSource.CLEANUP_TIMESTAMP) { event.getBibEntry().setField(StandardField.MODIFICATIONDATE, preferencesService.getTimestampPreferences().now()); } } }
1,245
40.533333
160
java
null
jabref-main/src/main/java/org/jabref/gui/WaitForSaveFinishedDialog.java
package org.jabref.gui; import java.util.List; import javafx.concurrent.Task; import org.jabref.logic.l10n.Localization; /** * Dialog shown when closing of application needs to wait for a save operation to finish. */ public class WaitForSaveFinishedDialog { private final DialogService dialogService; public WaitForSaveFinishedDialog(DialogService dialogService) { this.dialogService = dialogService; } public void showAndWait(List<LibraryTab> LibraryTabs) { if (LibraryTabs.stream().anyMatch(LibraryTab::isSaving)) { Task<Void> waitForSaveFinished = new Task<>() { @Override protected Void call() throws Exception { while (LibraryTabs.stream().anyMatch(LibraryTab::isSaving)) { if (isCancelled()) { return null; } else { Thread.sleep(100); } } return null; } }; dialogService.showProgressDialog( Localization.lang("Please wait..."), Localization.lang("Waiting for save operation to finish") + "...", waitForSaveFinished ); } } }
1,328
29.204545
89
java
null
jabref-main/src/main/java/org/jabref/gui/actions/Action.java
package org.jabref.gui.actions; import java.util.Optional; import org.jabref.gui.icon.JabRefIcon; import org.jabref.gui.keyboard.KeyBinding; public interface Action { default Optional<JabRefIcon> getIcon() { return Optional.empty(); } default Optional<KeyBinding> getKeyBinding() { return Optional.empty(); } String getText(); default String getDescription() { return ""; } }
434
17.913043
50
java
null
jabref-main/src/main/java/org/jabref/gui/actions/ActionFactory.java
package org.jabref.gui.actions; import java.lang.reflect.InaccessibleObjectException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Objects; import javafx.beans.binding.BooleanExpression; import javafx.scene.control.Button; import javafx.scene.control.ButtonBase; import javafx.scene.control.CheckMenuItem; import javafx.scene.control.Label; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.scene.control.Tooltip; import org.jabref.gui.keyboard.KeyBindingRepository; import org.jabref.model.strings.StringUtil; import com.sun.javafx.scene.control.ContextMenuContent; import com.tobiasdiez.easybind.EasyBind; import de.saxsys.mvvmfx.utils.commands.Command; import org.controlsfx.control.action.ActionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Helper class to create and style controls according to an {@link Action}. */ public class ActionFactory { private static final Logger LOGGER = LoggerFactory.getLogger(ActionFactory.class); private final KeyBindingRepository keyBindingRepository; public ActionFactory(KeyBindingRepository keyBindingRepository) { this.keyBindingRepository = Objects.requireNonNull(keyBindingRepository); } /** * For some reason the graphic is not set correctly by the {@link ActionUtils} class, so we have to fix this by hand */ private static void setGraphic(MenuItem node, Action action) { node.graphicProperty().unbind(); action.getIcon().ifPresent(icon -> node.setGraphic(icon.getGraphicNode())); } /* * Returns MenuItemContainer node associated with this menu item * which can contain: * 1. label node of type Label for displaying menu item text, * 2. right node of type Label for displaying accelerator text, * or an arrow if it's a Menu, * 3. graphic node for displaying menu item icon, and * 4. left node for displaying either radio button or check box. * * This is basically rewritten impl_styleableGetNode() which * should not be used since it's marked as deprecated. */ private static Label getAssociatedNode(MenuItem menuItem) { ContextMenuContent.MenuItemContainer container = (ContextMenuContent.MenuItemContainer) menuItem.getStyleableNode(); if (container == null) { return null; } else { // We have to use reflection to get the associated label try { Method getLabel = ContextMenuContent.MenuItemContainer.class.getDeclaredMethod("getLabel"); getLabel.setAccessible(true); return (Label) getLabel.invoke(container); } catch (InaccessibleObjectException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { LOGGER.warn("Could not get label of menu item", e); } } return null; } public MenuItem configureMenuItem(Action action, Command command, MenuItem menuItem) { ActionUtils.configureMenuItem(new JabRefAction(action, command, keyBindingRepository, Sources.FromMenu), menuItem); setGraphic(menuItem, action); // Show tooltips if (command instanceof SimpleCommand simpleCommand) { EasyBind.subscribe( simpleCommand.statusMessageProperty(), message -> { Label label = getAssociatedNode(menuItem); if (label != null) { label.setMouseTransparent(false); if (StringUtil.isBlank(message)) { label.setTooltip(null); } else { label.setTooltip(new Tooltip(message)); } } } ); } return menuItem; } public MenuItem createMenuItem(Action action, Command command) { MenuItem menuItem = new MenuItem(); configureMenuItem(action, command, menuItem); return menuItem; } public CheckMenuItem createCheckMenuItem(Action action, Command command, boolean selected) { CheckMenuItem checkMenuItem = ActionUtils.createCheckMenuItem(new JabRefAction(action, command, keyBindingRepository, Sources.FromMenu)); checkMenuItem.setSelected(selected); setGraphic(checkMenuItem, action); return checkMenuItem; } public CheckMenuItem createCheckMenuItem(Action action, Command command, BooleanExpression selectedBinding) { CheckMenuItem checkMenuItem = ActionUtils.createCheckMenuItem(new JabRefAction(action, command, keyBindingRepository, Sources.FromMenu)); EasyBind.subscribe(selectedBinding, checkMenuItem::setSelected); setGraphic(checkMenuItem, action); return checkMenuItem; } public Menu createMenu(Action action) { Menu menu = ActionUtils.createMenu(new JabRefAction(action, keyBindingRepository)); // For some reason the graphic is not set correctly, so let's fix this setGraphic(menu, action); return menu; } public Menu createSubMenu(Action action, MenuItem... children) { Menu menu = createMenu(action); menu.getItems().addAll(children); return menu; } public Button createIconButton(Action action, Command command) { Button button = ActionUtils.createButton(new JabRefAction(action, command, keyBindingRepository, Sources.FromButton), ActionUtils.ActionTextBehavior.HIDE); button.getStyleClass().setAll("icon-button"); // For some reason the graphic is not set correctly, so let's fix this button.graphicProperty().unbind(); action.getIcon().ifPresent(icon -> button.setGraphic(icon.getGraphicNode())); button.setFocusTraversable(false); // Prevent the buttons from stealing the focus return button; } public ButtonBase configureIconButton(Action action, Command command, ButtonBase button) { ActionUtils.unconfigureButton(button); ActionUtils.configureButton( new JabRefAction(action, command, keyBindingRepository, Sources.FromButton), button, ActionUtils.ActionTextBehavior.HIDE); button.getStyleClass().add("icon-button"); // For some reason the graphic is not set correctly, so let's fix this // ToDO: Find a way to reuse JabRefIconView button.graphicProperty().unbind(); action.getIcon().ifPresent(icon -> button.setGraphic(icon.getGraphicNode())); return button; } }
6,742
38.899408
163
java
null
jabref-main/src/main/java/org/jabref/gui/actions/ActionHelper.java
package org.jabref.gui.actions; import java.nio.file.Path; import java.util.Collections; import java.util.List; import java.util.Optional; import javafx.beans.binding.Binding; import javafx.beans.binding.Bindings; import javafx.beans.binding.BooleanExpression; import javafx.collections.ObservableList; import javafx.scene.control.TabPane; import org.jabref.gui.StateManager; import org.jabref.logic.shared.DatabaseLocation; import org.jabref.logic.util.io.FileUtil; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.LinkedFile; import org.jabref.model.entry.field.Field; import org.jabref.preferences.PreferencesService; import com.tobiasdiez.easybind.EasyBind; import com.tobiasdiez.easybind.EasyBinding; public class ActionHelper { public static BooleanExpression needsDatabase(StateManager stateManager) { return stateManager.activeDatabaseProperty().isPresent(); } public static BooleanExpression needsSharedDatabase(StateManager stateManager) { EasyBinding<Boolean> binding = EasyBind.map(stateManager.activeDatabaseProperty(), context -> context.filter(c -> c.getLocation() == DatabaseLocation.SHARED).isPresent()); return BooleanExpression.booleanExpression(binding); } public static BooleanExpression needsStudyDatabase(StateManager stateManager) { EasyBinding<Boolean> binding = EasyBind.map(stateManager.activeDatabaseProperty(), context -> context.filter(BibDatabaseContext::isStudy).isPresent()); return BooleanExpression.booleanExpression(binding); } public static BooleanExpression needsEntriesSelected(StateManager stateManager) { return Bindings.isNotEmpty(stateManager.getSelectedEntries()); } public static BooleanExpression needsEntriesSelected(int numberOfEntries, StateManager stateManager) { return Bindings.createBooleanBinding(() -> stateManager.getSelectedEntries().size() == numberOfEntries, stateManager.getSelectedEntries()); } public static BooleanExpression isFieldSetForSelectedEntry(Field field, StateManager stateManager) { return isAnyFieldSetForSelectedEntry(Collections.singletonList(field), stateManager); } public static BooleanExpression isAnyFieldSetForSelectedEntry(List<Field> fields, StateManager stateManager) { ObservableList<BibEntry> selectedEntries = stateManager.getSelectedEntries(); Binding<Boolean> fieldsAreSet = EasyBind.valueAt(selectedEntries, 0) .mapObservable(entry -> Bindings.createBooleanBinding(() -> { return entry.getFields().stream().anyMatch(fields::contains); }, entry.getFieldsObservable())) .orElseOpt(false); return BooleanExpression.booleanExpression(fieldsAreSet); } public static BooleanExpression isFilePresentForSelectedEntry(StateManager stateManager, PreferencesService preferencesService) { ObservableList<BibEntry> selectedEntries = stateManager.getSelectedEntries(); Binding<Boolean> fileIsPresent = EasyBind.valueAt(selectedEntries, 0).mapOpt(entry -> { List<LinkedFile> files = entry.getFiles(); if ((entry.getFiles().size() > 0) && stateManager.getActiveDatabase().isPresent()) { if (files.get(0).isOnlineLink()) { return true; } Optional<Path> filename = FileUtil.find( stateManager.getActiveDatabase().get(), files.get(0).getLink(), preferencesService.getFilePreferences()); return filename.isPresent(); } else { return false; } }).orElseOpt(false); return BooleanExpression.booleanExpression(fileIsPresent); } /** * Check if at least one of the selected entries has linked files * <br> * Used in {@link org.jabref.gui.maintable.OpenExternalFileAction} when multiple entries selected * * @param stateManager manager for the state of the GUI * @return a boolean binding */ public static BooleanExpression hasLinkedFileForSelectedEntries(StateManager stateManager) { return BooleanExpression.booleanExpression(EasyBind.reduce(stateManager.getSelectedEntries(), entries -> entries.anyMatch(entry -> !entry.getFiles().isEmpty()))); } public static BooleanExpression isOpenMultiDatabase(TabPane tabbedPane) { return Bindings.size(tabbedPane.getTabs()).greaterThan(1); } }
4,776
44.495238
179
java
null
jabref-main/src/main/java/org/jabref/gui/actions/JabRefAction.java
package org.jabref.gui.actions; import java.util.Map; import javafx.beans.binding.Bindings; import org.jabref.gui.Globals; import org.jabref.gui.keyboard.KeyBindingRepository; import de.saxsys.mvvmfx.utils.commands.Command; /** * Wrapper around one of our actions from {@link Action} to convert them to controlsfx {@link org.controlsfx.control.action.Action}. */ class JabRefAction extends org.controlsfx.control.action.Action { public JabRefAction(Action action, KeyBindingRepository keyBindingRepository) { super(action.getText()); action.getIcon() .ifPresent(icon -> setGraphic(icon.getGraphicNode())); action.getKeyBinding() .ifPresent(keyBinding -> keyBindingRepository.getKeyCombination(keyBinding).ifPresent(combination -> setAccelerator(combination))); setLongText(action.getDescription()); } public JabRefAction(Action action, Command command, KeyBindingRepository keyBindingRepository) { this(action, command, keyBindingRepository, null); } /** * especially for the track execute when the action run the same function but from different source. * * @param source is a string contains the source, for example "button" */ public JabRefAction(Action action, Command command, KeyBindingRepository keyBindingRepository, Sources source) { this(action, keyBindingRepository); setEventHandler(event -> { command.execute(); if (source == null) { trackExecute(getActionName(action, command)); } else { trackUserActionSource(getActionName(action, command), source); } }); disabledProperty().bind(command.executableProperty().not()); if (command instanceof SimpleCommand ourCommand) { longTextProperty().bind(Bindings.concat(action.getDescription(), ourCommand.statusMessageProperty())); } } private String getActionName(Action action, Command command) { if (command.getClass().isAnonymousClass()) { return action.getText(); } else { String commandName = command.getClass().getSimpleName(); if (commandName.contains("EditAction") || commandName.contains("CopyMoreAction") || commandName.contains("CopyCitationAction") || commandName.contains("PreviewSwitchAction") || commandName.contains("SaveAction")) { return command.toString(); } else { return commandName; } } } private void trackExecute(String actionName) { Globals.getTelemetryClient() .ifPresent(telemetryClient -> telemetryClient.trackEvent(actionName)); } private void trackUserActionSource(String actionName, Sources source) { Globals.getTelemetryClient().ifPresent(telemetryClient -> telemetryClient.trackEvent( actionName, Map.of("Source", source.toString()), Map.of())); } }
3,110
36.035714
145
java
null
jabref-main/src/main/java/org/jabref/gui/actions/SimpleCommand.java
package org.jabref.gui.actions; import javafx.beans.property.ReadOnlyDoubleProperty; import javafx.beans.property.ReadOnlyStringProperty; import javafx.beans.property.ReadOnlyStringWrapper; import org.jabref.gui.util.BindingsHelper; import de.saxsys.mvvmfx.utils.commands.CommandBase; /** * A simple command that does not track progress of the action. */ public abstract class SimpleCommand extends CommandBase { protected ReadOnlyStringWrapper statusMessage = new ReadOnlyStringWrapper(""); public String getStatusMessage() { return statusMessage.get(); } public ReadOnlyStringProperty statusMessageProperty() { return statusMessage.getReadOnlyProperty(); } @Override public double getProgress() { return 0; } @Override public ReadOnlyDoubleProperty progressProperty() { return null; } public void setExecutable(boolean executable) { this.executable.bind(BindingsHelper.constantOf(executable)); } }
1,004
24.125
82
java
null
jabref-main/src/main/java/org/jabref/gui/actions/Sources.java
package org.jabref.gui.actions; public enum Sources { FromButton, FromMenu }
86
11.428571
31
java
null
jabref-main/src/main/java/org/jabref/gui/actions/StandardActions.java
package org.jabref.gui.actions; import java.util.Optional; import org.jabref.gui.icon.IconTheme; import org.jabref.gui.icon.JabRefIcon; import org.jabref.gui.keyboard.KeyBinding; import org.jabref.logic.l10n.Localization; public enum StandardActions implements Action { COPY_MORE(Localization.lang("Copy") + "..."), COPY_TITLE(Localization.lang("Copy title"), KeyBinding.COPY_TITLE), COPY_KEY(Localization.lang("Copy citation key"), KeyBinding.COPY_CITATION_KEY), COPY_CITE_KEY(Localization.lang("Copy \\cite{citation key}"), KeyBinding.COPY_CITE_CITATION_KEY), COPY_KEY_AND_TITLE(Localization.lang("Copy citation key and title"), KeyBinding.COPY_CITATION_KEY_AND_TITLE), COPY_KEY_AND_LINK(Localization.lang("Copy citation key and link"), KeyBinding.COPY_CITATION_KEY_AND_LINK), COPY_CITATION_HTML(Localization.lang("Copy citation (html)"), KeyBinding.COPY_PREVIEW), COPY_CITATION_TEXT(Localization.lang("Copy citation (text)")), COPY_CITATION_PREVIEW(Localization.lang("Copy preview"), KeyBinding.COPY_PREVIEW), EXPORT_TO_CLIPBOARD(Localization.lang("Export to clipboard"), IconTheme.JabRefIcons.EXPORT_TO_CLIPBOARD), EXPORT_SELECTED_TO_CLIPBOARD(Localization.lang("Export selected entries to clipboard"), IconTheme.JabRefIcons.EXPORT_TO_CLIPBOARD), COPY(Localization.lang("Copy"), IconTheme.JabRefIcons.COPY, KeyBinding.COPY), PASTE(Localization.lang("Paste"), IconTheme.JabRefIcons.PASTE, KeyBinding.PASTE), CUT(Localization.lang("Cut"), IconTheme.JabRefIcons.CUT, KeyBinding.CUT), DELETE(Localization.lang("Delete"), IconTheme.JabRefIcons.DELETE_ENTRY), DELETE_ENTRY(Localization.lang("Delete entry"), IconTheme.JabRefIcons.DELETE_ENTRY, KeyBinding.DELETE_ENTRY), SEND(Localization.lang("Send"), IconTheme.JabRefIcons.EMAIL), SEND_AS_EMAIL(Localization.lang("As Email")), SEND_TO_KINDLE(Localization.lang("To Kindle")), REBUILD_FULLTEXT_SEARCH_INDEX(Localization.lang("Rebuild fulltext search index"), IconTheme.JabRefIcons.FILE), OPEN_EXTERNAL_FILE(Localization.lang("Open file"), IconTheme.JabRefIcons.FILE, KeyBinding.OPEN_FILE), OPEN_URL(Localization.lang("Open URL or DOI"), IconTheme.JabRefIcons.WWW, KeyBinding.OPEN_URL_OR_DOI), SEARCH_SHORTSCIENCE(Localization.lang("Search ShortScience")), MERGE_WITH_FETCHED_ENTRY(Localization.lang("Get bibliographic data from %0", "DOI/ISBN/...")), ATTACH_FILE(Localization.lang("Attach file"), IconTheme.JabRefIcons.ATTACH_FILE), ATTACH_FILE_FROM_URL(Localization.lang("Attach file from URL"), IconTheme.JabRefIcons.DOWNLOAD_FILE), PRIORITY(Localization.lang("Priority"), IconTheme.JabRefIcons.PRIORITY), CLEAR_PRIORITY(Localization.lang("Clear priority")), PRIORITY_HIGH(Localization.lang("Set priority to high"), IconTheme.JabRefIcons.PRIORITY_HIGH), PRIORITY_MEDIUM(Localization.lang("Set priority to medium"), IconTheme.JabRefIcons.PRIORITY_MEDIUM), PRIORITY_LOW(Localization.lang("Set priority to low"), IconTheme.JabRefIcons.PRIORITY_LOW), QUALITY(Localization.lang("Quality"), IconTheme.JabRefIcons.QUALITY), QUALITY_ASSURED(Localization.lang("Toggle quality assured"), IconTheme.JabRefIcons.QUALITY_ASSURED), RANKING(Localization.lang("Rank"), IconTheme.JabRefIcons.RANKING), CLEAR_RANK(Localization.lang("Clear rank")), RANK_1(Localization.lang("Set rank to one"), IconTheme.JabRefIcons.RANK1), RANK_2(Localization.lang("Set rank to two"), IconTheme.JabRefIcons.RANK2), RANK_3(Localization.lang("Set rank to three"), IconTheme.JabRefIcons.RANK3), RANK_4(Localization.lang("Set rank to four"), IconTheme.JabRefIcons.RANK4), RANK_5(Localization.lang("Set rank to five"), IconTheme.JabRefIcons.RANK5), PRINTED(Localization.lang("Printed"), IconTheme.JabRefIcons.PRINTED), TOGGLE_PRINTED(Localization.lang("Toggle print status"), IconTheme.JabRefIcons.PRINTED), READ_STATUS(Localization.lang("Read status"), IconTheme.JabRefIcons.READ_STATUS), CLEAR_READ_STATUS(Localization.lang("Clear read status"), KeyBinding.CLEAR_READ_STATUS), READ(Localization.lang("Set read status to read"), IconTheme.JabRefIcons.READ_STATUS_READ, KeyBinding.READ), SKIMMED(Localization.lang("Set read status to skimmed"), IconTheme.JabRefIcons.READ_STATUS_SKIMMED, KeyBinding.SKIMMED), RELEVANCE(Localization.lang("Relevance"), IconTheme.JabRefIcons.RELEVANCE), RELEVANT(Localization.lang("Toggle relevance"), IconTheme.JabRefIcons.RELEVANCE), NEW_LIBRARY(Localization.lang("New library"), IconTheme.JabRefIcons.NEW), OPEN_LIBRARY(Localization.lang("Open library"), IconTheme.JabRefIcons.OPEN, KeyBinding.OPEN_DATABASE), IMPORT(Localization.lang("Import"), IconTheme.JabRefIcons.IMPORT), EXPORT(Localization.lang("Export"), IconTheme.JabRefIcons.EXPORT, KeyBinding.EXPORT), SAVE_LIBRARY(Localization.lang("Save library"), IconTheme.JabRefIcons.SAVE, KeyBinding.SAVE_DATABASE), SAVE_LIBRARY_AS(Localization.lang("Save library as..."), KeyBinding.SAVE_DATABASE_AS), SAVE_SELECTED_AS_PLAIN_BIBTEX(Localization.lang("Save selected as plain BibTeX...")), SAVE_ALL(Localization.lang("Save all"), Localization.lang("Save all open libraries"), IconTheme.JabRefIcons.SAVE_ALL, KeyBinding.SAVE_ALL), IMPORT_INTO_NEW_LIBRARY(Localization.lang("Import into new library"), KeyBinding.IMPORT_INTO_NEW_DATABASE), IMPORT_INTO_CURRENT_LIBRARY(Localization.lang("Import into current library"), KeyBinding.IMPORT_INTO_CURRENT_DATABASE), EXPORT_ALL(Localization.lang("Export all entries")), REMOTE_DB(Localization.lang("Shared database"), IconTheme.JabRefIcons.REMOTE_DATABASE), EXPORT_SELECTED(Localization.lang("Export selected entries"), KeyBinding.EXPORT_SELECTED), CONNECT_TO_SHARED_DB(Localization.lang("Connect to shared database"), IconTheme.JabRefIcons.CONNECT_DB), PULL_CHANGES_FROM_SHARED_DB(Localization.lang("Pull changes from shared database"), KeyBinding.PULL_CHANGES_FROM_SHARED_DATABASE), CLOSE_LIBRARY(Localization.lang("Close library"), Localization.lang("Close the current library"), IconTheme.JabRefIcons.CLOSE, KeyBinding.CLOSE_DATABASE), CLOSE_OTHER_LIBRARIES(Localization.lang("Close others"), Localization.lang("Close other libraries"), IconTheme.JabRefIcons.CLOSE), CLOSE_ALL_LIBRARIES(Localization.lang("Close all"), Localization.lang("Close all libraries"), IconTheme.JabRefIcons.CLOSE), QUIT(Localization.lang("Quit"), Localization.lang("Quit JabRef"), IconTheme.JabRefIcons.CLOSE_JABREF, KeyBinding.QUIT_JABREF), UNDO(Localization.lang("Undo"), IconTheme.JabRefIcons.UNDO, KeyBinding.UNDO), REDO(Localization.lang("Redo"), IconTheme.JabRefIcons.REDO, KeyBinding.REDO), REPLACE_ALL(Localization.lang("Find and replace"), KeyBinding.REPLACE_STRING), MANAGE_KEYWORDS(Localization.lang("Manage keywords")), MASS_SET_FIELDS(Localization.lang("Manage field names & content")), AUTOMATIC_FIELD_EDITOR(Localization.lang("Automatic field editor")), TOGGLE_GROUPS(Localization.lang("Groups"), IconTheme.JabRefIcons.TOGGLE_GROUPS, KeyBinding.TOGGLE_GROUPS_INTERFACE), TOOGLE_OO(Localization.lang("OpenOffice/LibreOffice"), IconTheme.JabRefIcons.FILE_OPENOFFICE, KeyBinding.OPEN_OPEN_OFFICE_LIBRE_OFFICE_CONNECTION), TOGGLE_WEB_SEARCH(Localization.lang("Web search"), Localization.lang("Toggle web search interface"), IconTheme.JabRefIcons.WWW, KeyBinding.WEB_SEARCH), PARSE_LATEX(Localization.lang("Search for citations in LaTeX files..."), IconTheme.JabRefIcons.LATEX_CITATIONS), NEW_SUB_LIBRARY_FROM_AUX(Localization.lang("New sublibrary based on AUX file") + "...", Localization.lang("New BibTeX sublibrary") + Localization.lang("This feature generates a new library based on which entries are needed in an existing LaTeX document."), IconTheme.JabRefIcons.NEW), WRITE_METADATA_TO_PDF(Localization.lang("Write metadata to PDF files"), Localization.lang("Will write metadata to the PDFs linked from selected entries."), KeyBinding.WRITE_METADATA_TO_PDF), START_NEW_STUDY(Localization.lang("Start new systematic literature review")), UPDATE_SEARCH_RESULTS_OF_STUDY(Localization.lang("Update study search results")), EDIT_EXISTING_STUDY(Localization.lang("Manage study definition")), OPEN_DATABASE_FOLDER(Localization.lang("Reveal in file explorer")), OPEN_FOLDER(Localization.lang("Open folder"), Localization.lang("Open folder"), IconTheme.JabRefIcons.FOLDER, KeyBinding.OPEN_FOLDER), OPEN_FILE(Localization.lang("Open file"), Localization.lang("Open file"), IconTheme.JabRefIcons.FILE, KeyBinding.OPEN_FILE), OPEN_CONSOLE(Localization.lang("Open terminal here"), Localization.lang("Open terminal here"), IconTheme.JabRefIcons.CONSOLE, KeyBinding.OPEN_CONSOLE), COPY_LINKED_FILES(Localization.lang("Copy linked files to folder...")), COPY_DOI(Localization.lang("Copy DOI")), COPY_DOI_URL(Localization.lang("Copy DOI url")), ABBREVIATE(Localization.lang("Abbreviate journal names")), ABBREVIATE_DEFAULT(Localization.lang("default"), Localization.lang("Abbreviate journal names of the selected entries (DEFAULT abbreviation)"), KeyBinding.ABBREVIATE), ABBREVIATE_DOTLESS(Localization.lang("dotless"), Localization.lang("Abbreviate journal names of the selected entries (DOTLESS abbreviation)")), ABBREVIATE_SHORTEST_UNIQUE(Localization.lang("shortest unique"), Localization.lang("Abbreviate journal names of the selected entries (SHORTEST UNIQUE abbreviation)")), UNABBREVIATE(Localization.lang("Unabbreviate journal names"), Localization.lang("Unabbreviate journal names of the selected entries"), KeyBinding.UNABBREVIATE), MANAGE_CUSTOM_EXPORTS(Localization.lang("Manage custom exports")), MANAGE_CUSTOM_IMPORTS(Localization.lang("Manage custom imports")), CUSTOMIZE_ENTRY_TYPES(Localization.lang("Customize entry types")), SETUP_GENERAL_FIELDS(Localization.lang("Set up general fields")), MANAGE_PROTECTED_TERMS(Localization.lang("Manage protected terms")), CITATION_KEY_PATTERN(Localization.lang("Citation key patterns")), SHOW_PREFS(Localization.lang("Preferences"), IconTheme.JabRefIcons.PREFERENCES), MANAGE_JOURNALS(Localization.lang("Manage journal abbreviations")), CUSTOMIZE_KEYBINDING(Localization.lang("Customize key bindings"), IconTheme.JabRefIcons.KEY_BINDINGS), EDIT_ENTRY(Localization.lang("Open entry editor"), IconTheme.JabRefIcons.EDIT_ENTRY, KeyBinding.EDIT_ENTRY), SHOW_PDF_VIEWER(Localization.lang("Open document viewer"), IconTheme.JabRefIcons.PDF_FILE), NEXT_PREVIEW_STYLE(Localization.lang("Next preview style"), KeyBinding.NEXT_PREVIEW_LAYOUT), PREVIOUS_PREVIEW_STYLE(Localization.lang("Previous preview style"), KeyBinding.PREVIOUS_PREVIEW_LAYOUT), SELECT_ALL(Localization.lang("Select all"), KeyBinding.SELECT_ALL), UNSELECT_ALL(Localization.lang("Unselect all")), EXPAND_ALL(Localization.lang("Expand all")), COLLAPSE_ALL(Localization.lang("Collapse all")), NEW_ENTRY(Localization.lang("New entry"), IconTheme.JabRefIcons.ADD_ENTRY, KeyBinding.NEW_ENTRY), NEW_ARTICLE(Localization.lang("New article"), IconTheme.JabRefIcons.ADD_ARTICLE), NEW_ENTRY_FROM_PLAIN_TEXT(Localization.lang("New entry from plain text"), IconTheme.JabRefIcons.NEW_ENTRY_FROM_PLAIN_TEXT, KeyBinding.NEW_ENTRY_FROM_PLAIN_TEXT), LIBRARY_PROPERTIES(Localization.lang("Library properties")), FIND_DUPLICATES(Localization.lang("Find duplicates"), IconTheme.JabRefIcons.FIND_DUPLICATES), MERGE_ENTRIES(Localization.lang("Merge entries"), IconTheme.JabRefIcons.MERGE_ENTRIES, KeyBinding.MERGE_ENTRIES), RESOLVE_DUPLICATE_KEYS(Localization.lang("Resolve duplicate citation keys"), Localization.lang("Find and remove duplicate citation keys"), KeyBinding.RESOLVE_DUPLICATE_CITATION_KEYS), CHECK_INTEGRITY(Localization.lang("Check integrity"), KeyBinding.CHECK_INTEGRITY), FIND_UNLINKED_FILES(Localization.lang("Search for unlinked local files"), IconTheme.JabRefIcons.SEARCH, KeyBinding.FIND_UNLINKED_FILES), AUTO_LINK_FILES(Localization.lang("Automatically set file links"), IconTheme.JabRefIcons.AUTO_FILE_LINK, KeyBinding.AUTOMATICALLY_LINK_FILES), LOOKUP_DOC_IDENTIFIER(Localization.lang("Search document identifier online")), LOOKUP_FULLTEXT(Localization.lang("Search full text documents online"), IconTheme.JabRefIcons.FILE_SEARCH, KeyBinding.DOWNLOAD_FULL_TEXT), GENERATE_CITE_KEY(Localization.lang("Generate citation key"), IconTheme.JabRefIcons.MAKE_KEY, KeyBinding.AUTOGENERATE_CITATION_KEYS), GENERATE_CITE_KEYS(Localization.lang("Generate citation keys"), IconTheme.JabRefIcons.MAKE_KEY, KeyBinding.AUTOGENERATE_CITATION_KEYS), DOWNLOAD_FULL_TEXT(Localization.lang("Search full text documents online"), IconTheme.JabRefIcons.FILE_SEARCH, KeyBinding.DOWNLOAD_FULL_TEXT), CLEANUP_ENTRIES(Localization.lang("Cleanup entries"), IconTheme.JabRefIcons.CLEANUP_ENTRIES, KeyBinding.CLEANUP), SET_FILE_LINKS(Localization.lang("Automatically set file links"), KeyBinding.AUTOMATICALLY_LINK_FILES), EDIT_FILE_LINK(Localization.lang("Edit"), IconTheme.JabRefIcons.EDIT, KeyBinding.EDIT_ENTRY), DOWNLOAD_FILE(Localization.lang("Download file"), IconTheme.JabRefIcons.DOWNLOAD_FILE), RENAME_FILE_TO_PATTERN(Localization.lang("Rename file to defined pattern"), IconTheme.JabRefIcons.AUTO_RENAME), RENAME_FILE_TO_NAME(Localization.lang("Rename file to a given name"), IconTheme.JabRefIcons.RENAME, KeyBinding.REPLACE_STRING), MOVE_FILE_TO_FOLDER(Localization.lang("Move file to file directory"), IconTheme.JabRefIcons.MOVE_TO_FOLDER), MOVE_FILE_TO_FOLDER_AND_RENAME(Localization.lang("Move file to file directory and rename file")), COPY_FILE_TO_FOLDER(Localization.lang("Copy linked file to folder..."), IconTheme.JabRefIcons.COPY_TO_FOLDER, KeyBinding.COPY), REMOVE_LINK(Localization.lang("Remove link"), IconTheme.JabRefIcons.REMOVE_LINK), DELETE_FILE(Localization.lang("Permanently delete local file"), IconTheme.JabRefIcons.DELETE_FILE, KeyBinding.DELETE_ENTRY), HELP(Localization.lang("Online help"), IconTheme.JabRefIcons.HELP, KeyBinding.HELP), HELP_KEY_PATTERNS(Localization.lang("Help on key patterns"), IconTheme.JabRefIcons.HELP, KeyBinding.HELP), HELP_REGEX_SEARCH(Localization.lang("Help on regular expression search"), IconTheme.JabRefIcons.HELP, KeyBinding.HELP), HELP_NAME_FORMATTER(Localization.lang("Help on Name Formatting"), IconTheme.JabRefIcons.HELP, KeyBinding.HELP), HELP_SPECIAL_FIELDS(Localization.lang("Help on special fields"), IconTheme.JabRefIcons.HELP, KeyBinding.HELP), WEB_MENU(Localization.lang("JabRef resources")), OPEN_WEBPAGE(Localization.lang("Website"), Localization.lang("Opens JabRef's website"), IconTheme.JabRefIcons.HOME), OPEN_FACEBOOK("Facebook", Localization.lang("Opens JabRef's Facebook page"), IconTheme.JabRefIcons.FACEBOOK), OPEN_TWITTER("Twitter", Localization.lang("Opens JabRef's Twitter page"), IconTheme.JabRefIcons.TWITTER), OPEN_BLOG(Localization.lang("Blog"), Localization.lang("Opens JabRef's blog"), IconTheme.JabRefIcons.BLOG), OPEN_DEV_VERSION_LINK(Localization.lang("Development version"), Localization.lang("Opens a link where the current development version can be downloaded")), OPEN_CHANGELOG(Localization.lang("View change log"), Localization.lang("See what has been changed in the JabRef versions")), OPEN_GITHUB("GitHub", Localization.lang("Opens JabRef's GitHub page"), IconTheme.JabRefIcons.GITHUB), DONATE(Localization.lang("Donate to JabRef"), Localization.lang("Donate to JabRef"), IconTheme.JabRefIcons.DONATE), OPEN_FORUM(Localization.lang("Online help forum"), Localization.lang("Online help forum"), IconTheme.JabRefIcons.FORUM), ERROR_CONSOLE(Localization.lang("View event log"), Localization.lang("Display all error messages")), SEARCH_FOR_UPDATES(Localization.lang("Check for updates")), ABOUT(Localization.lang("About JabRef"), Localization.lang("About JabRef")), EDIT_LIST(Localization.lang("Edit"), IconTheme.JabRefIcons.EDIT), VIEW_LIST(Localization.lang("View"), IconTheme.JabRefIcons.FILE), REMOVE_LIST(Localization.lang("Remove"), IconTheme.JabRefIcons.REMOVE), RELOAD_LIST(Localization.lang("Reload"), IconTheme.JabRefIcons.REFRESH), GROUP_REMOVE(Localization.lang("Remove group")), GROUP_REMOVE_KEEP_SUBGROUPS(Localization.lang("Keep subgroups")), GROUP_REMOVE_WITH_SUBGROUPS(Localization.lang("Also remove subgroups")), GROUP_EDIT(Localization.lang("Edit group")), GROUP_SUBGROUP_ADD(Localization.lang("Add subgroup")), GROUP_SUBGROUP_REMOVE(Localization.lang("Remove subgroups")), GROUP_SUBGROUP_SORT(Localization.lang("Sort subgroups A-Z")), GROUP_ENTRIES_ADD(Localization.lang("Add selected entries to this group")), GROUP_ENTRIES_REMOVE(Localization.lang("Remove selected entries from this group")); private final String text; private final String description; private final Optional<JabRefIcon> icon; private final Optional<KeyBinding> keyBinding; StandardActions(String text) { this(text, ""); } StandardActions(String text, IconTheme.JabRefIcons icon) { this.text = text; this.description = ""; this.icon = Optional.of(icon); this.keyBinding = Optional.empty(); } StandardActions(String text, IconTheme.JabRefIcons icon, KeyBinding keyBinding) { this.text = text; this.description = ""; this.icon = Optional.of(icon); this.keyBinding = Optional.of(keyBinding); } StandardActions(String text, String description, IconTheme.JabRefIcons icon) { this.text = text; this.description = description; this.icon = Optional.of(icon); this.keyBinding = Optional.empty(); } StandardActions(String text, String description, IconTheme.JabRefIcons icon, KeyBinding keyBinding) { this.text = text; this.description = description; this.icon = Optional.of(icon); this.keyBinding = Optional.of(keyBinding); } StandardActions(String text, KeyBinding keyBinding) { this.text = text; this.description = ""; this.keyBinding = Optional.of(keyBinding); this.icon = Optional.empty(); } StandardActions(String text, String description) { this.text = text; this.description = description; this.icon = Optional.empty(); this.keyBinding = Optional.empty(); } StandardActions(String text, String description, KeyBinding keyBinding) { this.text = text; this.description = description; this.icon = Optional.empty(); this.keyBinding = Optional.of(keyBinding); } @Override public Optional<JabRefIcon> getIcon() { return icon; } @Override public Optional<KeyBinding> getKeyBinding() { return keyBinding; } @Override public String getText() { return text; } @Override public String getDescription() { return description; } }
19,105
69.501845
288
java
null
jabref-main/src/main/java/org/jabref/gui/autocompleter/AppendPersonNamesStrategy.java
package org.jabref.gui.autocompleter; public class AppendPersonNamesStrategy extends AppendWordsStrategy { /** * true if the input should be split at a single white space instead of the usual delimiter " and " for names. * Useful if the input consists of a list of last names. */ private final boolean separationBySpace; public AppendPersonNamesStrategy() { this(false); } public AppendPersonNamesStrategy(boolean separationBySpace) { this.separationBySpace = separationBySpace; } @Override public String getDelimiter() { if (this.separationBySpace) { return " "; } else { return " and "; } } }
715
24.571429
114
java
null
jabref-main/src/main/java/org/jabref/gui/autocompleter/AppendWordsStrategy.java
package org.jabref.gui.autocompleter; import java.util.Locale; public class AppendWordsStrategy implements AutoCompletionStrategy { protected String getDelimiter() { return " "; } @Override public AutoCompletionInput analyze(String input) { return determinePrefixAndReturnRemainder(input, getDelimiter()); } private AutoCompletionInput determinePrefixAndReturnRemainder(String input, String delimiter) { int index = input.toLowerCase(Locale.ROOT).lastIndexOf(delimiter); if (index >= 0) { String prefix = input.substring(0, index + delimiter.length()); String rest = input.substring(index + delimiter.length()); return new AutoCompletionInput(prefix, rest); } else { return new AutoCompletionInput("", input); } } }
845
30.333333
99
java
null
jabref-main/src/main/java/org/jabref/gui/autocompleter/AutoCompleteFirstNameMode.java
package org.jabref.gui.autocompleter; /** * <ul> * <li>For "ONLY_FULL", the auto completer returns the full name, e.g. "Smith, Bob"</li> * <li>For "ONLY_ABBREVIATED", the auto completer returns the first name abbreviated, e.g. "Smith, B."</li> * <li>For "BOTH", the auto completer returns both versions.</li> * </ul> */ public enum AutoCompleteFirstNameMode { ONLY_FULL, ONLY_ABBREVIATED, BOTH; public static AutoCompleteFirstNameMode parse(String input) { try { return AutoCompleteFirstNameMode.valueOf(input); } catch (IllegalArgumentException ex) { // Should only occur when preferences are set directly via preferences.put and not via setFirstnameMode return AutoCompleteFirstNameMode.BOTH; } } }
795
32.166667
115
java
null
jabref-main/src/main/java/org/jabref/gui/autocompleter/AutoCompletePreferences.java
package org.jabref.gui.autocompleter; import java.util.Set; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableSet; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldFactory; public class AutoCompletePreferences { public enum NameFormat { LAST_FIRST, FIRST_LAST, BOTH } private final BooleanProperty shouldAutoComplete; private final ObjectProperty<AutoCompleteFirstNameMode> firstNameMode; private final ObjectProperty<NameFormat> nameFormat; private final ObservableSet<Field> completeFields; public AutoCompletePreferences(boolean shouldAutoComplete, AutoCompleteFirstNameMode firstNameMode, NameFormat nameFormat, Set<Field> completeFields) { this.shouldAutoComplete = new SimpleBooleanProperty(shouldAutoComplete); this.firstNameMode = new SimpleObjectProperty<>(firstNameMode); this.nameFormat = new SimpleObjectProperty<>(nameFormat); this.completeFields = FXCollections.observableSet(completeFields); } public boolean shouldAutoComplete() { return shouldAutoComplete.get(); } public BooleanProperty autoCompleteProperty() { return shouldAutoComplete; } public void setAutoComplete(boolean shouldAutoComplete) { this.shouldAutoComplete.set(shouldAutoComplete); } /** * Returns how the first names are handled. */ public AutoCompleteFirstNameMode getFirstNameMode() { return firstNameMode.get(); } public ObjectProperty<AutoCompleteFirstNameMode> firstNameModeProperty() { return firstNameMode; } public void setFirstNameMode(AutoCompleteFirstNameMode firstNameMode) { this.firstNameMode.set(firstNameMode); } public NameFormat getNameFormat() { return nameFormat.get(); } public ObjectProperty<NameFormat> nameFormatProperty() { return nameFormat; } public void setNameFormat(NameFormat nameFormat) { this.nameFormat.set(nameFormat); } /** * Returns the list of fields for which autocomplete is enabled * * @return List of field names */ public ObservableSet<Field> getCompleteFields() { return completeFields; } public String getCompleteNamesAsString() { return FieldFactory.serializeFieldsList(completeFields); } }
2,687
29.545455
80
java
null
jabref-main/src/main/java/org/jabref/gui/autocompleter/AutoCompletionInput.java
package org.jabref.gui.autocompleter; public class AutoCompletionInput { private String unfinishedPart; private String prefix; public AutoCompletionInput(String prefix, String unfinishedPart) { this.prefix = prefix; this.unfinishedPart = unfinishedPart; } public String getUnfinishedPart() { return unfinishedPart; } public String getPrefix() { return prefix; } }
432
20.65
70
java
null
jabref-main/src/main/java/org/jabref/gui/autocompleter/AutoCompletionStrategy.java
package org.jabref.gui.autocompleter; public interface AutoCompletionStrategy { AutoCompletionInput analyze(String input); }
130
20.833333
46
java
null
jabref-main/src/main/java/org/jabref/gui/autocompleter/AutoCompletionTextInputBinding.java
/** * Copyright (c) 2014, 2015, ControlsFX * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of ControlsFX, any associated website, nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CONTROLSFX BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jabref.gui.autocompleter; import java.util.Collection; import javafx.beans.value.ChangeListener; import javafx.scene.control.TextInputControl; import javafx.util.Callback; import javafx.util.StringConverter; import org.jabref.gui.util.DefaultTaskExecutor; import org.controlsfx.control.textfield.AutoCompletionBinding; /** * Represents a binding between a text input control and an auto-completion popup * This class is a slightly modified version of {@link impl.org.controlsfx.autocompletion.AutoCompletionTextFieldBinding} * that works with general text input controls instead of just text fields. */ public class AutoCompletionTextInputBinding<T> extends AutoCompletionBinding<T> { /** * String converter to be used to convert suggestions to strings. */ private StringConverter<T> converter; private AutoCompletionStrategy inputAnalyzer; private final ChangeListener<String> textChangeListener = (obs, oldText, newText) -> { if (getCompletionTarget().isFocused()) { setUserInputText(newText); } }; private boolean showOnFocus; private final ChangeListener<Boolean> focusChangedListener = (obs, oldFocused, newFocused) -> { if (newFocused) { if (showOnFocus) { setUserInputText(getCompletionTarget().getText()); } } else { hidePopup(); } }; /** * Creates a new auto-completion binding between the given textInputControl * and the given suggestion provider. */ private AutoCompletionTextInputBinding(final TextInputControl textInputControl, Callback<ISuggestionRequest, Collection<T>> suggestionProvider) { this(textInputControl, suggestionProvider, AutoCompletionTextInputBinding.defaultStringConverter(), new ReplaceStrategy()); } private AutoCompletionTextInputBinding(final TextInputControl textInputControl, final Callback<ISuggestionRequest, Collection<T>> suggestionProvider, final StringConverter<T> converter) { this(textInputControl, suggestionProvider, converter, new ReplaceStrategy()); } private AutoCompletionTextInputBinding(final TextInputControl textInputControl, final Callback<ISuggestionRequest, Collection<T>> suggestionProvider, final StringConverter<T> converter, final AutoCompletionStrategy inputAnalyzer) { super(textInputControl, suggestionProvider, converter); this.converter = converter; this.inputAnalyzer = inputAnalyzer; getCompletionTarget().textProperty().addListener(textChangeListener); getCompletionTarget().focusedProperty().addListener(focusChangedListener); } private static <T> StringConverter<T> defaultStringConverter() { return new StringConverter<>() { @Override public String toString(T t) { return t == null ? null : t.toString(); } @SuppressWarnings("unchecked") @Override public T fromString(String string) { return (T) string; } }; } public static <T> void autoComplete(TextInputControl textArea, Callback<ISuggestionRequest, Collection<T>> suggestionProvider) { new AutoCompletionTextInputBinding<>(textArea, suggestionProvider); } public static <T> void autoComplete(TextInputControl textArea, Callback<ISuggestionRequest, Collection<T>> suggestionProvider, StringConverter<T> converter) { new AutoCompletionTextInputBinding<>(textArea, suggestionProvider, converter); } public static <T> AutoCompletionTextInputBinding<T> autoComplete(TextInputControl textArea, Callback<ISuggestionRequest, Collection<T>> suggestionProvider, StringConverter<T> converter, AutoCompletionStrategy inputAnalyzer) { return new AutoCompletionTextInputBinding<>(textArea, suggestionProvider, converter, inputAnalyzer); } public static <T> AutoCompletionTextInputBinding<T> autoComplete(TextInputControl textArea, Callback<ISuggestionRequest, Collection<T>> suggestionProvider, AutoCompletionStrategy inputAnalyzer) { return autoComplete(textArea, suggestionProvider, AutoCompletionTextInputBinding.defaultStringConverter(), inputAnalyzer); } private void setUserInputText(String newText) { if (newText == null) { newText = ""; } AutoCompletionInput input = inputAnalyzer.analyze(newText); DefaultTaskExecutor.runInJavaFXThread(() -> setUserInput(input.getUnfinishedPart())); } @Override public TextInputControl getCompletionTarget() { return (TextInputControl) super.getCompletionTarget(); } @Override public void dispose() { getCompletionTarget().textProperty().removeListener(textChangeListener); getCompletionTarget().focusedProperty().removeListener(focusChangedListener); } @Override protected void completeUserInput(T completion) { String completionText = converter.toString(completion); String inputText = getCompletionTarget().getText(); if (inputText == null) { inputText = ""; } AutoCompletionInput input = inputAnalyzer.analyze(inputText); String newText = input.getPrefix() + completionText; getCompletionTarget().setText(newText); getCompletionTarget().positionCaret(newText.length()); } public void setShowOnFocus(boolean showOnFocus) { this.showOnFocus = showOnFocus; } }
7,365
43.107784
229
java
null
jabref-main/src/main/java/org/jabref/gui/autocompleter/BibEntrySuggestionProvider.java
package org.jabref.gui.autocompleter; import java.util.Comparator; import java.util.stream.Stream; import org.jabref.logic.bibtex.comparator.EntryComparator; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.InternalField; import org.jabref.model.strings.StringUtil; import com.google.common.base.Equivalence; import org.controlsfx.control.textfield.AutoCompletionBinding; /** * Delivers possible completions as a list of {@link BibEntry} based on their citation key. */ public class BibEntrySuggestionProvider extends SuggestionProvider<BibEntry> { private final BibDatabase database; public BibEntrySuggestionProvider(BibDatabase database) { this.database = database; } @Override protected Equivalence<BibEntry> getEquivalence() { return Equivalence.equals().onResultOf(BibEntry::getCitationKey); } @Override protected Comparator<BibEntry> getComparator() { return new EntryComparator(false, true, InternalField.KEY_FIELD); } @Override protected boolean isMatch(BibEntry entry, AutoCompletionBinding.ISuggestionRequest request) { String userText = request.getUserText(); return entry.getCitationKey() .map(key -> StringUtil.containsIgnoreCase(key, userText)) .orElse(false); } @Override public Stream<BibEntry> getSource() { return database.getEntries().parallelStream(); } }
1,510
29.836735
97
java
null
jabref-main/src/main/java/org/jabref/gui/autocompleter/ContentSelectorSuggestionProvider.java
package org.jabref.gui.autocompleter; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.stream.Stream; /** * Enriches a suggestion provider by a given set of content selector values. */ public class ContentSelectorSuggestionProvider extends StringSuggestionProvider { private final SuggestionProvider<String> suggestionProvider; private final List<String> contentSelectorValues; public ContentSelectorSuggestionProvider(SuggestionProvider<String> suggestionProvider, List<String> contentSelectorValues) { this.suggestionProvider = suggestionProvider; this.contentSelectorValues = contentSelectorValues; } @Override public Stream<String> getSource() { return Stream.concat(contentSelectorValues.stream(), suggestionProvider.getSource()); } @Override public Collection<String> getPossibleSuggestions() { List<String> suggestions = new ArrayList<>(); if (suggestionProvider != null) { suggestions.addAll(suggestionProvider.getPossibleSuggestions()); } suggestions.addAll(contentSelectorValues); return suggestions; } }
1,233
31.473684
93
java
null
jabref-main/src/main/java/org/jabref/gui/autocompleter/EmptySuggestionProvider.java
package org.jabref.gui.autocompleter; import java.util.Comparator; import java.util.stream.Stream; import com.google.common.base.Equivalence; import org.controlsfx.control.textfield.AutoCompletionBinding; public class EmptySuggestionProvider extends SuggestionProvider<String> { @Override protected Equivalence<String> getEquivalence() { return Equivalence.equals().onResultOf(value -> value); } @Override protected Comparator<String> getComparator() { return Comparator.naturalOrder(); } @Override protected boolean isMatch(String candidate, AutoCompletionBinding.ISuggestionRequest request) { return false; } @Override public Stream<String> getSource() { return Stream.empty(); } }
770
24.7
99
java
null
jabref-main/src/main/java/org/jabref/gui/autocompleter/FieldValueSuggestionProvider.java
package org.jabref.gui.autocompleter; import java.util.Objects; import java.util.stream.Stream; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.field.Field; /** * Stores the full content of one field. */ class FieldValueSuggestionProvider extends StringSuggestionProvider { private final Field field; private final BibDatabase database; FieldValueSuggestionProvider(Field field, BibDatabase database) { this.field = Objects.requireNonNull(field); this.database = database; } @Override public Stream<String> getSource() { return database.getEntries().parallelStream().flatMap(entry -> entry.getField(field).stream()); } }
709
25.296296
103
java
null
jabref-main/src/main/java/org/jabref/gui/autocompleter/JournalsSuggestionProvider.java
package org.jabref.gui.autocompleter; import java.util.stream.Stream; import org.jabref.logic.journals.JournalAbbreviationRepository; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.field.Field; import com.google.common.collect.Streams; public class JournalsSuggestionProvider extends FieldValueSuggestionProvider { private final JournalAbbreviationRepository repository; JournalsSuggestionProvider(Field field, BibDatabase database, JournalAbbreviationRepository repository) { super(field, database); this.repository = repository; } @Override public Stream<String> getSource() { return Streams.concat(super.getSource(), repository.getFullNames().stream()); } }
746
27.730769
109
java
null
jabref-main/src/main/java/org/jabref/gui/autocompleter/PersonNameStringConverter.java
package org.jabref.gui.autocompleter; import javafx.util.StringConverter; import org.jabref.model.entry.Author; import org.jabref.model.entry.AuthorList; public class PersonNameStringConverter extends StringConverter<Author> { private final boolean autoCompFF; private final boolean autoCompLF; private final AutoCompleteFirstNameMode autoCompleteFirstNameMode; public PersonNameStringConverter(boolean autoCompFF, boolean autoCompLF, AutoCompleteFirstNameMode autoCompleteFirstNameMode) { this.autoCompFF = autoCompFF; this.autoCompLF = autoCompLF; this.autoCompleteFirstNameMode = autoCompleteFirstNameMode; } public PersonNameStringConverter(AutoCompletePreferences preferences) { switch (preferences.getNameFormat()) { case FIRST_LAST: autoCompFF = true; autoCompLF = false; break; case LAST_FIRST: autoCompFF = false; autoCompLF = true; break; default: case BOTH: autoCompFF = true; autoCompLF = true; break; } autoCompleteFirstNameMode = preferences.getFirstNameMode(); } @Override public String toString(Author author) { if (autoCompLF) { switch (autoCompleteFirstNameMode) { case ONLY_ABBREVIATED: return author.getLastFirst(true); case ONLY_FULL: return author.getLastFirst(false); case BOTH: return author.getLastFirst(true); default: break; } } if (autoCompFF) { switch (autoCompleteFirstNameMode) { case ONLY_ABBREVIATED: return author.getFirstLast(true); case ONLY_FULL: return author.getFirstLast(false); case BOTH: return author.getFirstLast(true); default: break; } } return author.getLastOnly(); } @Override public Author fromString(String string) { return AuthorList.parse(string).getAuthor(0); } }
2,302
30.121622
131
java