Please use the Apache issue tracking system for new NetBeans issues (https://issues.apache.org/jira/projects/NETBEANS0/issues) !!
View | Details | Raw Unified | Return to bug 32053 | Differences between
and this patch

Collapse All | Expand All

(-)core/bootstrap/src/org/netbeans/CLIHandler.java (-16 / +12 lines)
 Lines 86-94    Link Here 
86
    protected abstract int cli(Args args);
86
    protected abstract int cli(Args args);
87
    
87
    
88
    private static void showHelp(PrintWriter w, List handlers) {
88
    private static void showHelp(PrintWriter w, List handlers) {
89
        w.println("-?");
89
//        w.println("  -? or --help          Show this help information.");
90
        w.println("--help");
91
        w.println("  Show this help information.");
92
        Iterator it = handlers.iterator();
90
        Iterator it = handlers.iterator();
93
        while (it.hasNext()) {
91
        while (it.hasNext()) {
94
            ((CLIHandler)it.next()).usage(w);
92
            ((CLIHandler)it.next()).usage(w);
 Lines 128-143    Link Here 
128
    private static int notifyHandlers(Args args, List handlers, int when, boolean failOnUnknownOptions, boolean consume) {
126
    private static int notifyHandlers(Args args, List handlers, int when, boolean failOnUnknownOptions, boolean consume) {
129
        try {
127
        try {
130
            //System.err.println("notifyHandlers: handlers=" + handlers + " when=" + when + " args=" + Arrays.asList(args.getArguments()));
128
            //System.err.println("notifyHandlers: handlers=" + handlers + " when=" + when + " args=" + Arrays.asList(args.getArguments()));
131
            if (failOnUnknownOptions) {
129
            String[] argv = args.getArguments();
132
                String[] argv = args.getArguments();
130
            for (int i = 0; i < argv.length; i++) {
133
                for (int i = 0; i < argv.length; i++) {
131
                assert argv[i] != null;
134
                    assert argv[i] != null;
132
                if (argv[i].equals("-?") || argv[i].equals("--help") || argv[i].equals ("-help")) { // NOI18N
135
                    if (argv[i].equals("-?") || argv[i].equals("--help") || argv[i].equals ("-help")) { // NOI18N
133
                    PrintWriter w = new PrintWriter(args.getOutputStream());
136
                        PrintWriter w = new PrintWriter(args.getOutputStream());
134
                    showHelp(w, handlers);
137
                        showHelp(w, handlers);
135
                    w.flush();
138
                        w.flush();
136
                    return 2;
139
                        return 2;
140
                    }
141
                }
137
                }
142
            }
138
            }
143
            int r = 0;
139
            int r = 0;
 Lines 153-159    Link Here 
153
                }
149
                }
154
            }
150
            }
155
            if (failOnUnknownOptions) {
151
            if (failOnUnknownOptions) {
156
                String[] argv = args.getArguments();
152
                argv = args.getArguments();
157
                for (int i = 0; i < argv.length; i++) {
153
                for (int i = 0; i < argv.length; i++) {
158
                    if (argv[i] != null) {
154
                    if (argv[i] != null) {
159
                        // Unhandled option.
155
                        // Unhandled option.
 Lines 240-247    Link Here 
240
     * @param cleanLockFile removes lock file if it appears to be dead
236
     * @param cleanLockFile removes lock file if it appears to be dead
241
     * @return the file to be used as lock file or null parsing of args failed
237
     * @return the file to be used as lock file or null parsing of args failed
242
     */
238
     */
243
    static Status initialize(String[] args, ClassLoader loader, boolean failOnUnknownOptions, boolean cleanLockFile) {
239
    static Status initialize(String[] args, InputStream is, OutputStream os, ClassLoader loader, boolean failOnUnknownOptions, boolean cleanLockFile) {
244
        return initialize(new Args(args, System.in, System.err, System.getProperty ("user.dir")), (Integer)null, allCLIs(loader), failOnUnknownOptions, cleanLockFile);
240
        return initialize(new Args(args, is, os, System.getProperty ("user.dir")), (Integer)null, allCLIs(loader), failOnUnknownOptions, cleanLockFile);
245
    }
241
    }
246
    
242
    
247
    /**
243
    /**
(-)core/bootstrap/src/org/netbeans/Main.java (-10 / +48 lines)
 Lines 29-34    Link Here 
29
     * @throws Exception for lots of reasons
29
     * @throws Exception for lots of reasons
30
     */
30
     */
31
    public static void main (String args[]) throws Exception {
31
    public static void main (String args[]) throws Exception {
32
        java.lang.reflect.Method[] m = new java.lang.reflect.Method[1];
33
        int res = execute (args, System.in, System.err, m);
34
        if (res == -1) {
35
            // Connected to another running NB instance and succeeded in making a call.
36
            System.exit(0);
37
        } else if (res != 0) {
38
            // Some CLIHandler refused the invocation
39
            System.exit(res);
40
        }
41
42
        m[0].invoke (null, new Object[] { args });
43
    }
44
    
45
    /** Returns string describing usage of the system. Does that by talking to
46
     * all registered handlers and asking them to show their usage.
47
     *
48
     * @return the usage string for the system
49
     */
50
    public static String usage () throws Exception {
51
        java.io.ByteArrayOutputStream os = new java.io.ByteArrayOutputStream ();
52
        
53
        String[] newArgs = { "--help" };
54
        
55
        int res = execute (newArgs, System.in, os, null);
56
        return new String (os.toByteArray ());
57
    }
58
        
59
    /** Constructs the correct ClassLoader, finds main method to execute 
60
     * and invokes all registered CLIHandlers.
61
     *
62
     * @param args the arguments to pass to the handlers
63
     * @param reader the input stream reader for the handlers
64
     * @param writer the output stream for the handlers
65
     * @param methodToCall null or array with one item that will be set to 
66
     *   a method that shall be executed as the main application
67
     */
68
    private static int execute (
69
        String[] args, 
70
        java.io.InputStream reader, 
71
        java.io.OutputStream writer,
72
        java.lang.reflect.Method[] methodToCall
73
    ) throws Exception {     
32
        ArrayList list = new ArrayList ();
74
        ArrayList list = new ArrayList ();
33
75
34
        String home = System.getProperty ("netbeans.home"); // NOI18N
76
        String home = System.getProperty ("netbeans.home"); // NOI18N
 Lines 98-104    Link Here 
98
        //
140
        //
99
        
141
        
100
        CLIHandler.Status result;
142
        CLIHandler.Status result;
101
        result = CLIHandler.initialize(args, loader, true, false);
143
        result = CLIHandler.initialize(args, reader, writer, loader, true, false);
102
        if (result.getExitCode () == CLIHandler.Status.CANNOT_CONNECT) {
144
        if (result.getExitCode () == CLIHandler.Status.CANNOT_CONNECT) {
103
            int value = javax.swing.JOptionPane.showConfirmDialog (
145
            int value = javax.swing.JOptionPane.showConfirmDialog (
104
                null, 
146
                null, 
 Lines 108-127    Link Here 
108
                javax.swing.JOptionPane.WARNING_MESSAGE
150
                javax.swing.JOptionPane.WARNING_MESSAGE
109
            );
151
            );
110
            if (value == javax.swing.JOptionPane.OK_OPTION) {
152
            if (value == javax.swing.JOptionPane.OK_OPTION) {
111
                result = CLIHandler.initialize(args, loader, true, true);
153
                result = CLIHandler.initialize(args, reader, writer, loader, true, true);
112
            }
154
            }
113
            
155
            
114
        }
156
        }
115
        int res = result.getExitCode();
157
        
116
        if (res == -1) {
158
        if (methodToCall != null) {
117
            // Connected to another running NB instance and succeeded in making a call.
159
            methodToCall[0] = m;
118
            System.exit(0);
119
        } else if (res != 0) {
120
            // Some CLIHandler refused the invocation
121
            System.exit(res);
122
        }
160
        }
123
161
124
        m.invoke (null, new Object[] { args });
162
        return result.getExitCode ();
125
    }
163
    }
126
    
164
    
127
    /**
165
    /**
(-)core/release/bin/runide.sh (-32 / +16 lines)
 Lines 95-133    Link Here 
95
while [ $# -gt 0 ] ; do
95
while [ $# -gt 0 ] ; do
96
#    echo "Processing arg: '$1'"
96
#    echo "Processing arg: '$1'"
97
    case "$1" in
97
    case "$1" in
98
        -h|-help) cat >&2 <<EOF
98
        -h|-?|-help|--help) cat >&2 <<EOF
99
Usage: $0 {options} arguments
99
Usage: $0 {options} arguments
100
100
101
Options can be
101
General options:
102
102
  --help                show this help 
103
   -h -help
103
  --jdkhome <path>      path to JDK (could also be just JRE but some modules may not work!)
104
        shows usage
104
  -J<jvm_options>       passes <jvm_option> to JVM
105
   -?
105
Classpath options:
106
        help on more parameters (not interpreted by launcher)
106
  --cp:p <classpath>    prepends <classpath> to classpath
107
   -jdkhome <path>
107
  --cp:a <classpath>    appends <classpath> to classpath
108
        path to JDK (could also be just JRE but some modules may not work!)
109
   -userdir <path>
110
        specifies user settings directory (${userdir} by default)
111
   -J<jvm_options>
112
        passes <jvm_option> to JVM
113
Classpath options (normally you should NOT use these except to support -ui):
114
   -cp:p <classpath>
115
        prepends <classpath> to IDE's classpath
116
   -cp:a <classpath>
117
        appends <classpath> to IDE's classpath
118
119
All other options and arguments are passed to the IDE, so try -? for more.
120
Any options found in $HOME/ide.cfg or else $idehome/bin/ide.cfg
121
are treated as defaults (may be overridden).
122
See documentation for details.
123
EOF
108
EOF
124
exit 2
109
            # go on and print IDE options as well
125
;;
110
            args="$args --help" ;;
126
        -jdkhome) shift; if [ $# -gt 0 ] ; then jdkhome=$1; fi;;
111
        -jdkhome|--jdkhome) shift; if [ $# -gt 0 ] ; then jdkhome=$1; fi;;
127
        -userdir) shift; if [ $# -gt 0 ] ; then userdir=$1; fi;;
128
        # For compatibility only:
112
        # For compatibility only:
129
        -mainclass) shift; if [ $# -gt 0 ] ; then ide_class_option=-Dnetbeans.mainclass=$1; fi;;
113
        -mainclass) shift; if [ $# -gt 0 ] ; then ide_class_option=-Dnetbeans.mainclass=$1; fi;;
130
        -cp|-cp:a)
114
        -cp|-cp:a|--cp|--cp:a)
131
            shift;
115
            shift;
132
            if [ $# -gt 0 ] ; then
116
            if [ $# -gt 0 ] ; then
133
                if [ ! -z "$postfixcp" ] ; then postfixcp="$postfixcp:" ; fi
117
                if [ ! -z "$postfixcp" ] ; then postfixcp="$postfixcp:" ; fi
 Lines 135-141    Link Here 
135
            fi
119
            fi
136
            ;;
120
            ;;
137
        
121
        
138
        -cp:p)
122
        -cp:p|--cp:p)
139
            shift;
123
            shift;
140
            if [ $# -gt 0 ] ; then
124
            if [ $# -gt 0 ] ; then
141
                if [ ! -z "$prefixcp" ] ; then prefixcp="$prefixcp:" ; fi
125
                if [ ! -z "$prefixcp" ] ; then prefixcp="$prefixcp:" ; fi
 Lines 174-187    Link Here 
174
158
175
if [ -z "$jdkhome" ] ; then
159
if [ -z "$jdkhome" ] ; then
176
    echo "Cannot find JDK. Please set the JDK_HOME environment variable to point" >&2
160
    echo "Cannot find JDK. Please set the JDK_HOME environment variable to point" >&2
177
    echo "to your JDK installation directory, or use the -jdkhome switch" >&2
161
    echo "to your JDK installation directory, or use the --jdkhome switch" >&2
178
    exit 2
162
    exit 2
179
fi
163
fi
180
164
181
if [ ! -x "${jdkhome}/bin/java" ] ; then
165
if [ ! -x "${jdkhome}/bin/java" ] ; then
182
    echo "Cannot find JDK at ${jdkhome}. Please set the JDK_HOME" >&2
166
    echo "Cannot find JDK at ${jdkhome}. Please set the JDK_HOME" >&2
183
    echo "environment variable to point to your JDK installation directory," >&2
167
    echo "environment variable to point to your JDK installation directory," >&2
184
    echo "or use the -jdkhome switch" >&2
168
    echo "or use the --jdkhome switch" >&2
185
    exit 2
169
    exit 2
186
fi
170
fi
187
171
 Lines 190-196    Link Here 
190
#
174
#
191
175
192
if [ ! -z "$userdir" ] ; then
176
if [ ! -z "$userdir" ] ; then
193
    jargs="-Dnetbeans.user=\"${userdir}\" $jargs"
177
    args="--userdir \"${userdir}\" $args"
194
fi
178
fi
195
179
196
#
180
#
(-)core/src/org/netbeans/core/Bundle.properties (-10 / +10 lines)
 Lines 150-170    Link Here 
150
# NonGui
150
# NonGui
151
TEXT_help=\
151
TEXT_help=\
152
    Command-line options:\n\
152
    Command-line options:\n\
153
   \  -?                    show this help\n\
153
   \  --ui <UI class name>  use given UI class as the IDE's Look & Feel\n\
154
   \  -h (or -help)         show launcher-specific options\n\
154
   \  --fontsize <size>     use given number as the base font size of the\n\
155
   \  -ui <UI class name>   use given UI class as the IDE's Look & Feel\n\
156
   \  -fontsize <size>      use given number as the base font size of the\n\
157
   \                        IDE user interface, in points (11 default)\n\
155
   \                        IDE user interface, in points (11 default)\n\
158
   \                        (but see http://ui.netbeans.org/docs/ui/themes/themes.html)\n\
156
   \                        (but see http://ui.netbeans.org/docs/ui/themes/themes.html)\n\
159
   \  -locale <language[:country[:variant]]> use specified locale\n\
157
   \  --locale <language[:country[:variant]]> use specified locale\n\
160
    Rarer options (definitely not supported!):\n\
158
   \  --userdir <path>      user settings directory (${userdir} by default)\n\
161
   \  -branding <token>     use specified branding (- for default)\n\
159
   \  --branding <token>    use specified branding (- for default)
162
   \  -nologging            do not create the log file\n\
160
#   
163
   \  -nosplash             do not show the splash screen\n\
161
#   \  --nologging           do not create the log file\n\
164
   \  -nogui                just start up internals, do not show GUI
162
#   \  --nosplash            do not show the splash screen\n\
163
#   \  --nogui               just start up internals, do not show GUI
165
164
166
# error messages
165
# error messages
167
ERR_UIExpected=UI class name expected, using default UI...
166
ERR_UIExpected=UI class name expected, using default UI...
167
ERR_UserDirExpected=Directory expected after --userdir switch
168
ERR_UINotFound=UI class not found, using default UI...
168
ERR_UINotFound=UI class not found, using default UI...
169
ERR_UIError=An error occured when setting the specified UI, using default UI ...
169
ERR_UIError=An error occured when setting the specified UI, using default UI ...
170
ERR_FontSizeExpected=Font size expected, using default font size...
170
ERR_FontSizeExpected=Font size expected, using default font size...
(-)core/src/org/netbeans/core/CLIOptions.java (-8 / +27 lines)
 Lines 46-51    Link Here 
46
        return cli(arguments.getArguments());
46
        return cli(arguments.getArguments());
47
    }
47
    }
48
    
48
    
49
    private static boolean isOption (String value, String optionName) {
50
        if (value == null) return false;
51
        
52
        if (value.startsWith ("--")) {
53
            return value.substring (2).equals (optionName);
54
        } else if (value.startsWith ("-")) {
55
            return value.substring (1).equals (optionName);
56
        }
57
        return false;
58
    }
59
    
49
    final int cli(String[] args) {
60
    final int cli(String[] args) {
50
        // let's go through the command line
61
        // let's go through the command line
51
        for (int i = 0; i < args.length; i++) {
62
        for (int i = 0; i < args.length; i++) {
 Lines 53-67    Link Here 
53
                continue;
64
                continue;
54
            }
65
            }
55
            boolean used = true;
66
            boolean used = true;
56
            if (args[i].equalsIgnoreCase("-nogui")) { // NOI18N
67
            if (isOption (args[i], "nogui")) { // NOI18N
57
                System.getProperties().put("org.openide.TopManager", "org.netbeans.core.NonGui"); // NOI18N
68
                System.getProperties().put("org.openide.TopManager", "org.netbeans.core.NonGui"); // NOI18N
58
            } else if (args[i].equalsIgnoreCase("-nosplash")) { // NOI18N
69
            } else if (isOption (args[i], "nosplash")) { // NOI18N
59
                NonGui.noSplash = true;
70
                NonGui.noSplash = true;
60
            } else if (args[i].equalsIgnoreCase("-noinfo")) { // NOI18N
71
            } else if (isOption (args[i], "noinfo")) { // NOI18N
61
                // obsolete switch, ignore
72
                // obsolete switch, ignore
62
            } else if (args[i].equalsIgnoreCase("-nologging")) { // NOI18N
73
            } else if (isOption (args[i], "nologging")) { // NOI18N
63
                NonGui.noLogging = true;
74
                NonGui.noLogging = true;
64
            } else if (args[i].equalsIgnoreCase("-ui")) { // NOI18N
75
            } else if (isOption (args[i], "userdir")) { // NOI18N
76
                args[i] = null;
77
                try {
78
                    System.setProperty ("netbeans.user", args[++i]);
79
                } catch(ArrayIndexOutOfBoundsException e) {
80
                    System.err.println(NonGui.getString("ERR_UserDirExpected"));
81
                    return 2;
82
                }
83
            } else if (isOption (args[i], "ui")) { // NOI18N
65
                args[i] = null;
84
                args[i] = null;
66
                try {
85
                try {
67
                    NonGui.uiClass = Class.forName(args[++i]);
86
                    NonGui.uiClass = Class.forName(args[++i]);
 Lines 72-78    Link Here 
72
                    System.err.println(NonGui.getString("ERR_UINotFound"));
91
                    System.err.println(NonGui.getString("ERR_UINotFound"));
73
                    return 1;
92
                    return 1;
74
                }
93
                }
75
            } else if (args[i].equalsIgnoreCase("-fontsize")) { // NOI18N
94
            } else if (isOption (args[i], "fontsize")) { // NOI18N
76
                args[i] = null;
95
                args[i] = null;
77
                try {
96
                try {
78
                    NonGui.uiFontSize = Integer.parseInt(args[++i]);
97
                    NonGui.uiFontSize = Integer.parseInt(args[++i]);
 Lines 83-89    Link Here 
83
                    System.err.println(NonGui.getString("ERR_BadFontSize"));
102
                    System.err.println(NonGui.getString("ERR_BadFontSize"));
84
                    return 1;
103
                    return 1;
85
                }
104
                }
86
            } else if (args[i].equalsIgnoreCase("-locale")) { // NOI18N
105
            } else if (isOption (args[i], "locale")) { // NOI18N
87
                args[i] = null;
106
                args[i] = null;
88
                String localeParam = args[++i];
107
                String localeParam = args[++i];
89
                String language;
108
                String language;
 Lines 103-109    Link Here 
103
                        country = localeParam.substring(index1+1);
122
                        country = localeParam.substring(index1+1);
104
                }
123
                }
105
                Locale.setDefault(new Locale(language, country, variant));
124
                Locale.setDefault(new Locale(language, country, variant));
106
            } else if (args[i].equalsIgnoreCase("-branding")) { // NOI18N
125
            } else if (isOption (args[i], "branding")) { // NOI18N
107
                args[i] = null;
126
                args[i] = null;
108
                String branding = args[++i];
127
                String branding = args[++i];
109
                if (branding.equals("-")) branding = null; // NOI18N
128
                if (branding.equals("-")) branding = null; // NOI18N
(-)openide/src/org/openide/text/CloneableEditorSupport.java (-33 / +145 lines)
 Lines 106-114    Link Here 
106
    private EditorKit kit;
106
    private EditorKit kit;
107
107
108
    /** document we work with */
108
    /** document we work with */
109
    private StyledDocument doc;
109
    private DocReference docRef;
110
111
112
110
113
    /** Non default MIME type used to editing */
111
    /** Non default MIME type used to editing */
114
    private String mimeType;
112
    private String mimeType;
 Lines 251-256    Link Here 
251
    final EditorKit kit () {
249
    final EditorKit kit () {
252
        return kit;
250
        return kit;
253
    }
251
    }
252
    
253
    /** Getter for the document we are associated with.
254
     */
255
    final StyledDocument doc () {
256
        return doc (true);
257
    }
258
    /** Getter for the document we are associated with.
259
     * @param wait whether to wait for the result or not
260
     */
261
    final StyledDocument doc (boolean wait) {
262
        Object o = docRef;
263
        if (o instanceof StyledDocument) {
264
            return (StyledDocument)o;
265
        } else {
266
            DocReference ref = (DocReference)o;
267
            return ref == null ? null : (StyledDocument)ref.get (wait);
268
        }
269
    }
254
270
255
271
256
    /**
272
    /**
 Lines 377-392    Link Here 
377
        // in spite of that the document is not yet fully read in
393
        // in spite of that the document is not yet fully read in
378
394
379
        kit = createEditorKit ();
395
        kit = createEditorKit ();
380
        if (doc == null) {
396
        StyledDocument styled = doc ();
381
            doc = createStyledDocument (kit);
397
        if (styled == null) {
398
            styled = createStyledDocument (kit);
399
            docRef = new DocReference (styled);
382
        }
400
        }
383
        final StyledDocument docToLoad = doc;
384
        
401
        
385
        // The thread nume should be: "Loading document " + env; // NOI18N
402
        // The thread nume should be: "Loading document " + env; // NOI18N
386
        prepareTask = RequestProcessor.getDefault().post(new Runnable () {
403
        class R implements Runnable {
387
            
404
            private StyledDocument docToLoad;
388
            private boolean runningInAtomicLock;
405
            private boolean runningInAtomicLock;
389
            
406
            
407
            public R (StyledDocument style) {
408
                this.docToLoad = style;
409
            }
410
            
390
            public void run () {
411
            public void run () {
391
                
412
                
392
                // Run the operations under atomic lock primarily due
413
                // Run the operations under atomic lock primarily due
 Lines 398-405    Link Here 
398
419
399
                    // Add undoable listener after atomic change has finished
420
                    // Add undoable listener after atomic change has finished
400
                    synchronized (getLock()) {
421
                    synchronized (getLock()) {
401
                        if (doc == docToLoad) { // if document still valid
422
                        if (doc() == docToLoad && docToLoad != null) { // if document still valid
402
                            doc.addUndoableEditListener(getUndoRedo());
423
                            docToLoad.addUndoableEditListener(getUndoRedo());
403
                        }
424
                        }
404
                    }
425
                    }
405
426
 Lines 413-419    Link Here 
413
                    }
434
                    }
414
435
415
                    // Check whether the document to be loaded was not closed
436
                    // Check whether the document to be loaded was not closed
416
                    if (doc != docToLoad) {
437
                    if (doc() != docToLoad) {
417
                        return; // do not load closed document
438
                        return; // do not load closed document
418
                    }
439
                    }
419
                
440
                
 Lines 432-438    Link Here 
432
453
433
                                updateLineSet(true);
454
                                updateLineSet(true);
434
455
435
                                fireDocumentChange(doc, true);
456
                                fireDocumentChange(docToLoad, true);
436
457
437
                                clearDocument();
458
                                clearDocument();
438
                            }
459
                            }
 Lines 445-451    Link Here 
445
                        // assign before fireDocumentChange() as listener should be able to access getDocument()
466
                        // assign before fireDocumentChange() as listener should be able to access getDocument()
446
                        documentStatus = DOCUMENT_READY;
467
                        documentStatus = DOCUMENT_READY;
447
468
448
                        fireDocumentChange(doc, false);
469
                        fireDocumentChange(docToLoad, false);
449
470
450
                        // Confirm that whole loading succeeded
471
                        // Confirm that whole loading succeeded
451
                        targetStatus = DOCUMENT_READY;
472
                        targetStatus = DOCUMENT_READY;
 Lines 456-462    Link Here 
456
                          throw t;
477
                          throw t;
457
478
458
                    } finally {
479
                    } finally {
459
480
                        docToLoad = null;
460
                        synchronized (getLock()) {
481
                        synchronized (getLock()) {
461
                            documentStatus = targetStatus;
482
                            documentStatus = targetStatus;
462
483
 Lines 466-484    Link Here 
466
                    
487
                    
467
                }
488
                }
468
            }
489
            }
469
        });
490
        }
491
        prepareTask = RequestProcessor.getDefault().post(new R (styled));
470
492
471
        return prepareTask;
493
        return prepareTask;
472
    }
494
    }
473
    
495
    
474
    /** Clears the <code>doc</code> document. Helper method. */
496
    /** Clears the <code>doc</code> document. Helper method. */
475
    private void clearDocument() {
497
    private void clearDocument() {
476
        NbDocument.runAtomic(doc, new Runnable() {
498
        final StyledDocument style = doc ();
499
        if (style == null) return;
500
        
501
        NbDocument.runAtomic(style, new Runnable() {
477
             public void run() {
502
             public void run() {
478
                 try {
503
                 try {
479
                     doc.removeDocumentListener(getListener());
504
                     style.removeDocumentListener(getListener());
480
                     doc.remove(0, doc.getLength()); // remove all text
505
                     style.remove(0, style.getLength()); // remove all text
481
                     doc.addDocumentListener(getListener());
506
                     style.addDocumentListener(getListener());
482
                 } catch(BadLocationException ble) {
507
                 } catch(BadLocationException ble) {
483
                     ErrorManager.getDefault().notify(
508
                     ErrorManager.getDefault().notify(
484
                         ErrorManager.INFORMATIONAL, ble);
509
                         ErrorManager.INFORMATIONAL, ble);
 Lines 528-534    Link Here 
528
553
529
            case DOCUMENT_RELOADING: // proceed to DOCUMENT_READY
554
            case DOCUMENT_RELOADING: // proceed to DOCUMENT_READY
530
            case DOCUMENT_READY:
555
            case DOCUMENT_READY:
531
                return doc;
556
                return doc();
532
                
557
                
533
            default: // loading
558
            default: // loading
534
                try {
559
                try {
 Lines 563-569    Link Here 
563
                        // (possible only via LineListener->DocumentLine..).
588
                        // (possible only via LineListener->DocumentLine..).
564
                        // PENDING Needs to be tried to redesign DocumentLine to avoid this.
589
                        // PENDING Needs to be tried to redesign DocumentLine to avoid this.
565
                        if (LOCAL_LOAD_TASK.get() != null) {
590
                        if (LOCAL_LOAD_TASK.get() != null) {
566
                            return doc;
591
                            return doc();
567
                        }
592
                        }
568
        
593
        
569
                        try {
594
                        try {
 Lines 634-640    Link Here 
634
            // remember time of last save
659
            // remember time of last save
635
            lastSaveTime = System.currentTimeMillis();
660
            lastSaveTime = System.currentTimeMillis();
636
661
637
            notifyUnmodified ();
662
            doNotifyUnmodified ();
638
663
639
        } catch (BadLocationException ex) {
664
        } catch (BadLocationException ex) {
640
            ErrorManager.getDefault().notify(ex);
665
            ErrorManager.getDefault().notify(ex);
 Lines 861-866    Link Here 
861
    * @return <code>true</code> if document is loaded
886
    * @return <code>true</code> if document is loaded
862
    */
887
    */
863
    public boolean isDocumentLoaded() {
888
    public boolean isDocumentLoaded() {
889
        doc ();
864
        return loadTask != null;
890
        return loadTask != null;
865
    }
891
    }
866
892
 Lines 1022-1027    Link Here 
1022
    *  by calling <tt>prepareDocument()</tt>.
1048
    *  by calling <tt>prepareDocument()</tt>.
1023
    */
1049
    */
1024
    protected Task reloadDocument() {
1050
    protected Task reloadDocument() {
1051
        StyledDocument doc = doc ();
1025
        if (doc != null) {
1052
        if (doc != null) {
1026
            // UndoManager must be detached from document here because it will be attached in loadDocument()
1053
            // UndoManager must be detached from document here because it will be attached in loadDocument()
1027
            doc.removeUndoableEditListener (getUndoRedo ());
1054
            doc.removeUndoableEditListener (getUndoRedo ());
 Lines 1069-1075    Link Here 
1069
                                  )
1096
                                  )
1070
                              );
1097
                              );
1071
1098
1072
                              notifyUnmodified ();
1099
                              doNotifyUnmodified ();
1073
                              updateLineSet(true);
1100
                              updateLineSet(true);
1074
                          }
1101
                          }
1075
                      });
1102
                      });
 Lines 1134-1139    Link Here 
1134
        return sd;
1161
        return sd;
1135
    }
1162
    }
1136
    
1163
    
1164
    //
1165
    // Ensuring some behaviour is done when modified/unmodified
1166
    //
1167
    
1168
    private void doNotifyModified () {
1169
        notifyModified ();
1170
        docRef.hold (true);
1171
    }
1172
    
1173
    private void doNotifyUnmodified () {
1174
        notifyUnmodified ();
1175
        docRef.hold (false);
1176
    } 
1177
    
1178
    
1137
    /** Notification method called when the document become unmodified.
1179
    /** Notification method called when the document become unmodified.
1138
    * Called after save or after reload of document.
1180
    * Called after save or after reload of document.
1139
    * <P>
1181
    * <P>
 Lines 1230-1236    Link Here 
1230
    private Runnable createUndoTask() {
1272
    private Runnable createUndoTask() {
1231
        return new Runnable() {
1273
        return new Runnable() {
1232
            public void run() {
1274
            public void run() {
1233
                StyledDocument sd = doc;
1275
                StyledDocument sd = doc ();
1234
                if(sd == null) {
1276
                if(sd == null) {
1235
                    // #20883, doc can be null(!), doCloseDocument was faster.
1277
                    // #20883, doc can be null(!), doCloseDocument was faster.
1236
                    return;
1278
                    return;
 Lines 1269-1275    Link Here 
1269
    /** Allows access to the document without any checking.
1311
    /** Allows access to the document without any checking.
1270
    */
1312
    */
1271
    final StyledDocument getDocumentHack () {
1313
    final StyledDocument getDocumentHack () {
1272
        return doc;
1314
        return doc ();
1273
    }
1315
    }
1274
    
1316
    
1275
1317
 Lines 1295-1300    Link Here 
1295
1337
1296
            Line.Set oldSet = lineSet;
1338
            Line.Set oldSet = lineSet;
1297
1339
1340
            StyledDocument doc = doc ();
1298
            if (doc == null || documentStatus == DOCUMENT_RELOADING) {
1341
            if (doc == null || documentStatus == DOCUMENT_RELOADING) {
1299
                lineSet = new EditorSupportLineSet.Closed(CloneableEditorSupport.this);
1342
                lineSet = new EditorSupportLineSet.Closed(CloneableEditorSupport.this);
1300
            } else {
1343
            } else {
 Lines 1424-1438    Link Here 
1424
1467
1425
        // notifies the support that 
1468
        // notifies the support that 
1426
        env ().removePropertyChangeListener(getListener());
1469
        env ().removePropertyChangeListener(getListener());
1427
        notifyUnmodified ();
1470
        doNotifyUnmodified ();
1428
1471
1472
        StyledDocument doc = doc (false);
1429
        if (doc != null) {
1473
        if (doc != null) {
1430
            getUndoRedo().discardAllEdits();
1474
            getUndoRedo().discardAllEdits();
1431
            doc.removeUndoableEditListener (getUndoRedo ());
1475
            doc.removeUndoableEditListener (getUndoRedo ());
1432
            doc.removeDocumentListener(getListener());
1476
            doc.removeDocumentListener(getListener());
1433
        }
1477
        }
1434
1478
1435
        if (positionManager != null) {
1479
        if (positionManager != null && doc != null) {
1436
            positionManager.documentClosed ();
1480
            positionManager.documentClosed ();
1437
1481
1438
            documentStatus = DOCUMENT_NO;
1482
            documentStatus = DOCUMENT_NO;
 Lines 1440-1446    Link Here 
1440
        }
1484
        }
1441
1485
1442
        documentStatus = DOCUMENT_NO;
1486
        documentStatus = DOCUMENT_NO;
1443
        doc = null;
1487
        docRef = null;
1444
1488
1445
        kit = null;
1489
        kit = null;
1446
1490
 Lines 1459-1465    Link Here 
1459
                    return; // return if no document loaded
1503
                    return; // return if no document loaded
1460
            }
1504
            }
1461
1505
1462
            d = doc; // used with reload dialog - should not be null
1506
            d = doc (); // used with reload dialog - should not be null
1507
            
1508
            if (d == null) {
1509
                // no document loaded
1510
                return;
1511
            }
1463
        }
1512
        }
1464
1513
1465
        if (!doReload && !reloadDialogOpened) {
1514
        if (!doReload && !reloadDialogOpened) {
 Lines 1785-1798    Link Here 
1785
        * @param ev event describing the action
1834
        * @param ev event describing the action
1786
        */
1835
        */
1787
        public void insertUpdate(DocumentEvent ev) {
1836
        public void insertUpdate(DocumentEvent ev) {
1788
            notifyModified ();
1837
            doNotifyModified ();
1789
        }
1838
        }
1790
1839
1791
        /** Gives notification that a portion of the document has been removed.
1840
        /** Gives notification that a portion of the document has been removed.
1792
        * @param ev event describing the action
1841
        * @param ev event describing the action
1793
        */
1842
        */
1794
        public void removeUpdate(DocumentEvent ev) {
1843
        public void removeUpdate(DocumentEvent ev) {
1795
            notifyModified ();
1844
            doNotifyModified ();
1796
        }
1845
        }
1797
1846
1798
        /** Listener to changes in the Env.
1847
        /** Listener to changes in the Env.
 Lines 1826-1831    Link Here 
1826
        /** Initialization of the document.
1875
        /** Initialization of the document.
1827
        */
1876
        */
1828
        public void run () {
1877
        public void run () {
1878
                StyledDocument doc = doc ();
1829
//             synchronized (getLock ()) {
1879
//             synchronized (getLock ()) {
1830
                 /* Remove existing listener before running the loading task
1880
                 /* Remove existing listener before running the loading task
1831
                 * This should prevent firing of insertUpdate() during load (or reload)
1881
                 * This should prevent firing of insertUpdate() during load (or reload)
 Lines 2029-2035    Link Here 
2029
            super.redo();
2079
            super.redo();
2030
2080
2031
            if (saveTime == lastSaveTime) {
2081
            if (saveTime == lastSaveTime) {
2032
                notifyUnmodified();
2082
                doNotifyUnmodified();
2033
            }
2083
            }
2034
        }
2084
        }
2035
            
2085
            
 Lines 2064-2072    Link Here 
2064
            super.undo();
2114
            super.undo();
2065
2115
2066
            if (saveTime == lastSaveTime) {
2116
            if (saveTime == lastSaveTime) {
2067
                notifyUnmodified();
2117
                doNotifyUnmodified();
2068
            }
2118
            }
2069
        }
2119
        }
2070
2120
2121
    }
2122
    
2123
    /** Special reference holding the document.
2124
     */
2125
    private final class DocReference extends java.lang.ref.SoftReference 
2126
    implements Runnable {
2127
        /** hard reference to the document if marked as modified */
2128
        private StyledDocument hard;
2129
        /** has finalization been run */
2130
        private boolean finalized;
2131
        
2132
        public DocReference (StyledDocument doc) {
2133
            super (doc, org.openide.util.Utilities.activeReferenceQueue ());
2134
        }
2135
        
2136
        /** Called to notify the reference that it should hold or not hard 
2137
         * reference to the document.
2138
         * @param hard true if hard link should be hold
2139
         */
2140
        public void hold (boolean hard) {
2141
            if (hard) {
2142
                this.hard = (StyledDocument)super.get ();
2143
            } else {
2144
                this.hard = null;
2145
            }
2146
        }
2147
        
2148
        public void run () {
2149
            closeDocument ();
2150
            synchronized (this) {
2151
                finalized = true;
2152
                notifyAll ();
2153
            }
2154
        }
2155
        
2156
        public Object get () {
2157
            throw new IllegalStateException ("Not implemented exception"); // NOI18N
2158
        }
2159
        
2160
        /** Gets the document. 
2161
         * @param wait true whether to wait for finalization to finish or not
2162
         */
2163
        public Object get (boolean wait) {
2164
            for (;;) {
2165
                Object ret = super.get ();
2166
                if (ret != null || !wait) {
2167
                    return ret;
2168
                }
2169
                synchronized (this) {
2170
                    if (!finalized) {
2171
                        try {
2172
                            wait ();
2173
                        } catch (InterruptedException ex) {
2174
                            // go on and try once more
2175
                        }
2176
                    } else {
2177
                        return null;
2178
                    }
2179
                }
2180
            }
2181
        }
2182
        
2071
    }
2183
    }
2072
}
2184
}
(-)openide/src/org/openide/text/DocumentLine.java (-5 / +5 lines)
 Lines 805-811    Link Here 
805
        }
805
        }
806
806
807
        Set (StyledDocument doc, CloneableEditorSupport support) {
807
        Set (StyledDocument doc, CloneableEditorSupport support) {
808
            listener = new LineListener (doc, support);
808
            listener = new LineListener (support);
809
        }
809
        }
810
810
811
        
811
        
 Lines 822-828    Link Here 
822
                // revalidate all parts attached to this line
822
                // revalidate all parts attached to this line
823
                // that they are still part of the line
823
                // that they are still part of the line
824
                if(line instanceof DocumentLine) {
824
                if(line instanceof DocumentLine) {
825
                    ((DocumentLine)line).notifyChange(p0, this, listener.doc);
825
                    ((DocumentLine)line).notifyChange(p0, this, listener.support.doc ());
826
                }
826
                }
827
            }
827
            }
828
        }
828
        }
 Lines 890-896    Link Here 
890
        */
890
        */
891
        public Line getOriginal (int line) throws IndexOutOfBoundsException {
891
        public Line getOriginal (int line) throws IndexOutOfBoundsException {
892
            int newLine = listener.getLine (line);
892
            int newLine = listener.getLine (line);
893
            int offset = NbDocument.findLineOffset (listener.doc, newLine);
893
            int offset = NbDocument.findLineOffset (listener.support.doc (), newLine);
894
894
895
            return safelyRegisterLine(createLine(offset));
895
            return safelyRegisterLine(createLine(offset));
896
        }
896
        }
 Lines 901-907    Link Here 
901
        * @exception IndexOutOfBoundsException if <code>line</code> is invalid.
901
        * @exception IndexOutOfBoundsException if <code>line</code> is invalid.
902
        */
902
        */
903
        public Line getCurrent (int line) throws IndexOutOfBoundsException {
903
        public Line getCurrent (int line) throws IndexOutOfBoundsException {
904
            int offset = NbDocument.findLineOffset (listener.doc, line);
904
            int offset = NbDocument.findLineOffset (listener.support.doc (), line);
905
905
906
            return safelyRegisterLine(createLine(offset));
906
            return safelyRegisterLine(createLine(offset));
907
        }
907
        }
 Lines 929-935    Link Here 
929
                }
929
                }
930
            }
930
            }
931
            DocumentRenderer renderer = new DocumentRenderer ();
931
            DocumentRenderer renderer = new DocumentRenderer ();
932
            listener.doc.render (renderer);
932
            listener.support.doc ().render (renderer);
933
            return renderer.result;
933
            return renderer.result;
934
        }
934
        }
935
    }
935
    }
(-)openide/src/org/openide/text/LineListener.java (-4 / +5 lines)
 Lines 24-31    Link Here 
24
    implements javax.swing.event.DocumentListener {
24
    implements javax.swing.event.DocumentListener {
25
    /** original count of lines */
25
    /** original count of lines */
26
    private int orig;
26
    private int orig;
27
    /** document to work with */
28
    public final StyledDocument doc;
29
    /** root element of all lines */
27
    /** root element of all lines */
30
    private Element root;
28
    private Element root;
31
    /** last tested amount of lines */
29
    /** last tested amount of lines */
 Lines 38-45    Link Here 
38
    CloneableEditorSupport support;
36
    CloneableEditorSupport support;
39
    
37
    
40
    /** Creates new LineListener */
38
    /** Creates new LineListener */
41
    public LineListener (StyledDocument doc, CloneableEditorSupport support) {
39
    public LineListener (CloneableEditorSupport support) {
42
        this.doc = doc;
40
        StyledDocument doc = support.doc ();
41
        
43
        this.struct = new LineStruct ();
42
        this.struct = new LineStruct ();
44
        root = NbDocument.findLineRootElement (doc);
43
        root = NbDocument.findLineRootElement (doc);
45
        orig = lines = root.getElementCount ();
44
        orig = lines = root.getElementCount ();
 Lines 63-68    Link Here 
63
        int delta = lines - elem;
62
        int delta = lines - elem;
64
        lines = elem;
63
        lines = elem;
65
64
65
        StyledDocument doc = support.doc ();
66
        int lineNumber = NbDocument.findLineNumber (doc, p0.getOffset ());
66
        int lineNumber = NbDocument.findLineNumber (doc, p0.getOffset ());
67
        
67
        
68
        if (delta > 0) {
68
        if (delta > 0) {
 Lines 95-100    Link Here 
95
        int delta = elem - lines;
95
        int delta = elem - lines;
96
        lines = elem;
96
        lines = elem;
97
97
98
        StyledDocument doc = support.doc ();
98
        int lineNumber = NbDocument.findLineNumber (doc, p0.getOffset ());
99
        int lineNumber = NbDocument.findLineNumber (doc, p0.getOffset ());
99
        
100
        
100
        if (delta > 0) {
101
        if (delta > 0) {
(-)openide/src/org/openide/text/PositionRef.java (-14 / +9 lines)
 Lines 192-200    Link Here 
192
        /** support for the editor */
192
        /** support for the editor */
193
        transient private CloneableEditorSupport support;
193
        transient private CloneableEditorSupport support;
194
194
195
        /** the document for this manager or null if the manager is not in memory */
196
        transient private StyledDocument doc;
197
198
        static final long serialVersionUID =-4374030124265110801L;
195
        static final long serialVersionUID =-4374030124265110801L;
199
        /** Creates new manager
196
        /** Creates new manager
200
        * @param supp support to work with
197
        * @param supp support to work with
 Lines 254-261    Link Here 
254
        /** Converts all positions into document one.
251
        /** Converts all positions into document one.
255
        */
252
        */
256
        void documentOpened (StyledDocument doc) {
253
        void documentOpened (StyledDocument doc) {
257
            this.doc = doc;
258
259
            processPositions(true);
254
            processPositions(true);
260
        }
255
        }
261
256
 Lines 264-271    Link Here 
264
        */
259
        */
265
        void documentClosed () {
260
        void documentClosed () {
266
            processPositions(false);
261
            processPositions(false);
267
268
            doc = null;
269
        }
262
        }
270
        
263
        
271
        /** Puts/gets positions to/from memory. It also provides full
264
        /** Puts/gets positions to/from memory. It also provides full
 Lines 502-508    Link Here 
502
                        "Illegal PositionKind: " + pos + "[offset=" // NOI18N
495
                        "Illegal PositionKind: " + pos + "[offset=" // NOI18N
503
                        + offset + ",line=" // NOI18N
496
                        + offset + ",line=" // NOI18N
504
                        + line + ",column=" + column + "] in " // NOI18N
497
                        + line + ",column=" + column + "] in " // NOI18N
505
                        + doc + " used by " + support + "." // NOI18N
498
                        + support.doc() + " used by " + support + "." // NOI18N
506
                    );
499
                    );
507
                }
500
                }
508
                
501
                
 Lines 555-561    Link Here 
555
                        "Illegal OutKind[offset=" // NOI18N
548
                        "Illegal OutKind[offset=" // NOI18N
556
                        + offset + ",line=" // NOI18N
549
                        + offset + ",line=" // NOI18N
557
                        + line + ",column=" + column + "] in " // NOI18N
550
                        + line + ",column=" + column + "] in " // NOI18N
558
                        + doc + " used by " + support + "." // NOI18N
551
                        + support.doc () + " used by " + support + "." // NOI18N
559
                    );
552
                    );
560
                }
553
                }
561
                
554
                
 Lines 594-600    Link Here 
594
                        "Illegal OutKind[offset=" // NOI18N
587
                        "Illegal OutKind[offset=" // NOI18N
595
                        + offset + ",line=" // NOI18N
588
                        + offset + ",line=" // NOI18N
596
                        + line + ",column=" + column + "] in " // NOI18N
589
                        + line + ",column=" + column + "] in " // NOI18N
597
                        + doc + " used by " + support + "." // NOI18N
590
                        + support.doc () + " used by " + support + "." // NOI18N
598
                    );
591
                    );
599
                }
592
                }
600
                
593
                
 Lines 616-622    Link Here 
616
                if(offset < 0) {
609
                if(offset < 0) {
617
                    throw new IndexOutOfBoundsException(
610
                    throw new IndexOutOfBoundsException(
618
                        "Illegal OffsetKind[offset=" // NOI18N
611
                        "Illegal OffsetKind[offset=" // NOI18N
619
                        + offset + "] in " + doc + " used by " // NOI18N
612
                        + offset + "] in " + support.doc () + " used by " // NOI18N
620
                        + support + "." // NOI18N
613
                        + support + "." // NOI18N
621
                    );
614
                    );
622
                }
615
                }
 Lines 650-656    Link Here 
650
                if(offset < 0) {
643
                if(offset < 0) {
651
                    throw new IOException(
644
                    throw new IOException(
652
                        "Illegal OffsetKind[offset=" // NOI18N
645
                        "Illegal OffsetKind[offset=" // NOI18N
653
                        + offset + "] in " + doc + " used by " // NOI18N
646
                        + offset + "] in " + support.doc () + " used by " // NOI18N
654
                        + support + "." // NOI18N
647
                        + support + "." // NOI18N
655
                    );
648
                    );
656
                }
649
                }
 Lines 675-681    Link Here 
675
                    throw new IndexOutOfBoundsException(
668
                    throw new IndexOutOfBoundsException(
676
                        "Illegal LineKind[line=" // NOI18N
669
                        "Illegal LineKind[line=" // NOI18N
677
                        + line + ",column=" + column + "] in " // NOI18N
670
                        + line + ",column=" + column + "] in " // NOI18N
678
                        + doc + " used by " + support + "." // NOI18N
671
                        + support.doc () + " used by " + support + "." // NOI18N
679
                    );
672
                    );
680
                }
673
                }
681
                
674
                
 Lines 731-737    Link Here 
731
                    throw new IOException(
724
                    throw new IOException(
732
                        "Illegal LineKind[line=" // NOI18N
725
                        "Illegal LineKind[line=" // NOI18N
733
                        + line + ",column=" + column + "] in " // NOI18N
726
                        + line + ",column=" + column + "] in " // NOI18N
734
                        + doc + " used by " + support + "." // NOI18N
727
                        + support.doc () + " used by " + support + "." // NOI18N
735
                    );
728
                    );
736
                }
729
                }
737
                
730
                
 Lines 856-861    Link Here 
856
            }
849
            }
857
            
850
            
858
            void render() {
851
            void render() {
852
                StyledDocument doc = support.doc (false);
859
                if (doc != null) {
853
                if (doc != null) {
860
                    doc.render(this);
854
                    doc.render(this);
861
                } else {
855
                } else {
 Lines 902-907    Link Here 
902
            }
896
            }
903
            
897
            
904
            public void run() {
898
            public void run() {
899
                StyledDocument doc = support.doc (false);
905
                try {
900
                try {
906
                    switch (opCode) {
901
                    switch (opCode) {
907
                        case KIND_TO_MEMORY: {
902
                        case KIND_TO_MEMORY: {
(-)openide/test/unit/src/org/openide/text/CloneableEditorSupportTest.java (+39 lines)
 Lines 166-171    Link Here 
166
        assertGC ("Document can dissapear", ref);
166
        assertGC ("Document can dissapear", ref);
167
    }
167
    }
168
168
169
    public void testDocumentBeGarbageCollectedWhenNotModifiedButOpened () throws Exception {
170
        content = "Ahoj\nMyDoc";
171
        javax.swing.text.Document doc = support.openDocument ();
172
        assertNotNull (doc);
173
        
174
        java.lang.ref.WeakReference ref = new java.lang.ref.WeakReference (doc);
175
        doc = null;
176
        
177
        assertGC ("Document can dissapear", ref);
178
179
        assertFalse ("Document is not loaded", support.isDocumentLoaded ());
180
        assertTrue ("Can be closed without problems", support.close ());
181
    }
182
183
    public void testDocumentIsNotGCedIfModified () throws Exception {
184
        content = "Ahoj\nMyDoc";
185
        javax.swing.text.Document doc = support.openDocument ();
186
        assertNotNull (doc);
187
        doc.insertString (0, "Zmena", null);
188
        
189
        assertTrue ("Is modified", support.isModified ());
190
        
191
        java.lang.ref.WeakReference ref = new java.lang.ref.WeakReference (doc);
192
        doc = null;
193
194
        boolean ok;
195
        try {
196
            assertGC ("Should fail", ref);
197
            ok = false;
198
        } catch (AssertionFailedError expected) {
199
            ok = true;
200
        }
201
        if (!ok) {
202
            fail ("Document should not disappear, as it is modified");
203
        }
204
        
205
        assertTrue ("Document remains loaded", support.isDocumentLoaded ());
206
        
207
    }
169
    
208
    
170
    private void compareStreamWithString(InputStream is, String s) throws Exception{
209
    private void compareStreamWithString(InputStream is, String s) throws Exception{
171
        int i;
210
        int i;
(-)utilities/clisrc/org/netbeans/modules/openfile/cli/Handler.java (-70 / +51 lines)
 Lines 35-114    Link Here 
35
        return (Callback)Lookup.getDefault().lookup(Callback.class);
35
        return (Callback)Lookup.getDefault().lookup(Callback.class);
36
    }
36
    }
37
    
37
    
38
    private File findFile (File curDir, String name) {
39
        File f = new File(name);
40
        if (!f.isAbsolute()) {
41
            f = new File(curDir, name);
42
        }
43
        return f;
44
    }
45
    
46
    private int openFile (File curDir, CLIHandler.Args args, String[] argv, int i) {
47
        String s = argv[i];
48
        if (s == null) {
49
            log("Missing argument to --open", args);
50
            return 2;
51
        }
52
        argv[i] = null;
53
        Callback c = getCallback();
54
        if (c == null) {
55
            // XXX I18N required for cmdline?
56
            log("The User Utilities module must be installed for open-file functionality to work.", args);
57
            return 2;
58
        }
59
        int line = -1;
60
        File f = findFile (curDir, s);
61
        if (!f.exists()) {
62
            // Check if it is file:line syntax.
63
            int idx = s.lastIndexOf(':'); // NOI18N
64
            if (idx != -1) {
65
                try {
66
                    line = Integer.parseInt(s.substring(idx + 1)) - 1;
67
                    f = findFile (curDir, s.substring(0, idx));
68
                } catch (NumberFormatException e) {
69
                    // OK, leave as a filename
70
                }
71
            }
72
        }
73
        // Just make sure it was opened, then exit.
74
        boolean success = c.open(f, line, null);
75
        return success ? 0 : 1;
76
    }
77
    
38
    protected int cli(CLIHandler.Args args) {
78
    protected int cli(CLIHandler.Args args) {
39
        String[] argv = args.getArguments();
79
        String[] argv = args.getArguments();
40
        File curDir = args.getCurrentDirectory ();
80
        File curDir = args.getCurrentDirectory ();
41
        boolean wait = false;
42
        for (int i = 0; i < argv.length; i++) {
81
        for (int i = 0; i < argv.length; i++) {
43
            if (argv[i] == null) {
82
            if (argv[i] == null) {
44
                continue;
83
                continue;
45
            }
84
            }
46
            if (argv[i].equals("-open")) { // NOI18N
85
            if (argv[i].equals("--open") || argv[i].equals("-open")) { // NOI18N
47
                argv[i] = null;
86
                argv[i] = null;
48
                if (i == argv.length - 1) {
87
                if (i == argv.length - 1) {
49
                    log("Missing argument to -open", args);
88
                    log("Missing argument to --open", args);
50
                    return 2;
89
                    return 2;
51
                }
90
                }
52
                String s = argv[++i];
91
                i++;
53
                if (s == null) {
92
                while (i < argv.length && !argv[i].startsWith ("-")) {
54
                    log("Missing argument to -open", args);
93
                    int res = openFile (curDir, args, argv, i++);
55
                    return 2;
94
                    if (res != 0) {
56
                }
95
                        return res;
57
                argv[i] = null;
58
                Callback c = getCallback();
59
                if (c == null) {
60
                    // XXX I18N required for cmdline?
61
                    log("The User Utilities module must be installed for open-file functionality to work.", args);
62
                    return 2;
63
                }
64
                int line = -1;
65
                File f = new File(s);
66
                if (!f.isAbsolute()) {
67
                    f = new File(curDir, s);
68
                }
69
                if (!f.exists()) {
70
                    // Check if it is file:line syntax.
71
                    int idx = s.lastIndexOf(':'); // NOI18N
72
                    if (idx != -1) {
73
                        try {
74
                            line = Integer.parseInt(s.substring(idx + 1)) - 1;
75
                            f = new File(s.substring(0, idx));
76
                        } catch (NumberFormatException e) {
77
                            // OK, leave as a filename
78
                        }
79
                    }
96
                    }
80
                }
97
                }
81
                boolean success;
98
            } 
82
                if (wait) {
83
                    // Open it, and wait for it to be closed.
84
                    Callback.Waiter w = new Callback.Waiter() {
85
                        public synchronized void done() {
86
                            notify();
87
                        }
88
                    };
89
                    success = c.open(f, line, w);
90
                    /* XXX uncomment when implemented in module
91
                    if (success) {
92
                        try {
93
                            synchronized (w) {
94
                                w.wait();
95
                            }
96
                        } catch (InterruptedException e) {
97
                            e.printStackTrace();
98
                        }
99
                    }
100
                     */
101
                } else {
102
                    // Just make sure it was opened, then exit.
103
                    success = c.open(f, line, null);
104
                }
105
                if (!success) {
106
                    return 1;
107
                }
108
            } else if (argv[i].equals("-wait")) { // NOI18N
109
                argv[i] = null;
110
                wait = true;
111
            }
112
        }
99
        }
113
        // No problems.
100
        // No problems.
114
        return 0;
101
        return 0;
 Lines 122-136    Link Here 
122
    }
109
    }
123
    
110
    
124
    protected void usage(PrintWriter w) {
111
    protected void usage(PrintWriter w) {
125
        w.println("-open FILE");
112
        w.println("Open File Module options:");
126
        w.println("  Open FILE.");
113
        w.println("  --open FILE           open FILE.");
127
        w.println("-open FILE:LINE");
114
        w.println("  --open FILE:LINE      open FILE at line LINE (starting from 1).");
128
        w.println("  Open FILE at line LINE (starting from 1).");
129
        /* XXX uncomment when implemented in module
130
        w.println("-wait -open FILE[:LINE]");
131
        w.println("  Open FILE (maybe at line LINE), and wait until it is closed before exiting.");
132
        w.println("  (Currently unimplemented.)");
133
         */
134
    }
115
    }
135
    
116
    
136
}
117
}

Return to bug 32053
By use of this website, you agree to the NetBeans Policies and Terms of Use. © 2014, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo