scriptpad.js

来自「一个小公司要求给写的很简单的任务管理系统。」· JavaScript 代码 · 共 657 行 · 第 1/2 页

JS
657
字号
/** @(#)scriptpad.js	1.1 06/08/06** Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.** Redistribution and use in source and binary forms, with or without* modification, are permitted provided that the following conditions are met:** -Redistribution of source code must retain the above copyright notice, this*  list of conditions and the following disclaimer.** -Redistribution 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 Sun Microsystems, Inc. or the names of contributors may* be used to endorse or promote products derived from this software without* specific prior written permission.** This software is provided "AS IS," without a warranty of any kind. ALL* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.** You acknowledge that this software is not designed, licensed or intended* for use in the design, construction, operation or maintenance of any* nuclear facility.*//* * This script creates a simple Notepad-like interface, which  * serves as a simple script editor, runner. * * File dependency: * *    gui.js -> for basic GUI functions *//* * JavaImporter helps in avoiding pollution of JavaScript * global namespace. We can import multiple Java packages * with this and use the JavaImporter object with "with" * statement. */var guiPkgs = new JavaImporter(java.awt, java.awt.event,                         javax.swing, javax.swing.undo,                         javax.swing.event, javax.swing.text);with (guiPkgs) {        /*      * within this "with" statement all Java classes in      * packages defined in "guiPkgs" can be used as simple      * names instead of the fully qualified names.      */     // main entry point of the scriptpad application     function main() {        function createEditor() {            var c = new JTextArea();            c.setDragEnabled(true);            c.setFont(new Font("monospaced", Font.PLAIN, 12));            return c;        }        /*const*/ var titleSuffix = "- Scriptpad";        /*const*/ var defaultTitle = "Untitled" + titleSuffix;        // Scriptpad's main frame        var frame;        // Scriptpad's main editor        var editor;        // To track the current file name        var curFileName = null;        // To track whether the current document         // has been modified or not        var docChanged = false;        // check and alert user for unsaved        // but modified document                function checkDocChanged() {            if (docChanged) {                // ignore zero-content untitled document                if (curFileName == null &&                    editor.document.length == 0) {                    return;                }                if (confirm(                    "Do you want to save the changes?",                    "The document has changed")) {                    actionSave();                }            }        }        // set a document listener to track         // whether that is modified or not        function setDocListener() {            var doc = editor.getDocument();            docChanged = false;            doc.addDocumentListener(new DocumentListener() {                    equals: function(o) { return this === o; },                    toString: function() { return "doc listener"; },                    changeUpdate: function() { docChanged = true; },                    insertUpdate: function() { docChanged = true; },                    removeUpdate: function() { docChanged = true; },                });        }        // menu action functions        // "File" menu         // create a "new" document        function actionNew(){            checkDocChanged();            curFileName = null;            editor.setDocument(new PlainDocument());            setDocListener();            frame.setTitle(defaultTitle);            editor.revalidate();        }        // open an existing file        function actionOpen() {            checkDocChanged();            var f = fileDialog();            if (f == null) {                return;            }            if (f.isFile() && f.canRead()) {                                frame.setTitle(f.getName() + titleSuffix);                editor.setDocument(new PlainDocument());                var progress = new JProgressBar();                progress.setMinimum(0);                progress.setMaximum(f.length());                var doc = editor.getDocument();                var inp = new java.io.FileReader(f);                var buff = java.lang.reflect.Array.newInstance(                                java.lang.Character.TYPE, 4096);                var nch;                while ((nch = inp.read(buff, 0, buff.length)) != -1) {                    doc.insertString(doc.getLength(),                         new java.lang.String(buff, 0, nch), null);                    progress.setValue(progress.getValue() + nch);                }                inp.close();                curFileName = f.getAbsolutePath();                setDocListener();             } else {                error("Can not open file: " + f,                    "Error opening file: " + f);                                 }                       }        // open script from a URL        function actionOpenURL() {            checkDocChanged();            var url = prompt("Address:");            if (url == null) {                return;            }            try {                var u = new java.net.URL(url);                 editor.setDocument(new PlainDocument());                frame.setTitle(url + titleSuffix);                var progress = new JProgressBar();                progress.setMinimum(0);                progress.setIndeterminate(true);                var doc = editor.getDocument();                var inp = new java.io.InputStreamReader(u.openStream());                var buff = java.lang.reflect.Array.newInstance(                                java.lang.Character.TYPE, 4096);                var nch;                while ((nch = inp.read(buff, 0, buff.length)) != -1) {                    doc.insertString(doc.getLength(),                           new java.lang.String(buff, 0, nch), null);                    progress.setValue(progress.getValue() + nch);                }                    curFileName = null;                setDocListener();            } catch (e) {                error("Error opening URL: " + e,                      "Can not open URL: " + url);            }           }         // factored out "save" function used by         // save, save as menu actions        function save(file) {            var doc = editor.getDocument();            frame.setTitle(file.getName() + titleSuffix);            curFileName = file;            var progress = new JProgressBar();            progress.setMinimum(0);            progress.setMaximum(file.length());                        var out = new java.io.FileWriter(file);            var text = new Segment();            text.setPartialReturn(true);            var charsLeft = doc.getLength();            var offset = 0;            while (charsLeft > 0) {                doc.getText(offset, java.lang.Math.min(4096, charsLeft), text);                out.write(text.array, text.offset, text.count);                charsLeft -= text.count;                offset += text.count;                progress.setValue(offset);                java.lang.Thread.sleep(10);                           }            out.flush();            out.close();                       docChanged = false;                   }        // file-save as menu        function actionSaveAs() {            var ret = fileDialog(null, true);            if (ret == null) {                return;            }            save(ret);        }        // file-save menu        function actionSave() {                        if (curFileName) {                save(new java.io.File(curFileName));            } else {                actionSaveAs();            }        }        // exit from scriptpad        function actionExit() {            checkDocChanged();                       java.lang.System.exit(0);        }        // "Edit" menu         // cut the currently selected text        function actionCut() {            editor.cut();        }        // copy the currently selected text to clipboard        function actionCopy() {            editor.copy();        }        // paste clipboard content to document        function actionPaste() {            editor.paste();        }        // select all the text in editor        function actionSelectAll() {            editor.selectAll();        }        // "Tools" menu         // run the current document as JavaScript        function actionRun() {            var doc = editor.getDocument();            var script = doc.getText(0, doc.getLength());            var oldFile = engine.get(javax.script.ScriptEngine.FILENAME);            try {                if (this.engine == undefined) {                    var m = new javax.script.ScriptEngineManager();                    engine = m.getEngineByName("js");                }                engine.put(javax.script.ScriptEngine.FILENAME, frame.title);                engine.eval(script, context);            } catch (e) {                  error(e, "Script Error");                // e.rhinoException.printStackTrace();            } finally {                engine.put(javax.script.ScriptEngine.FILENAME, oldFile);            }        }        // "Examples" menu         // show given script as new document        function showScript(title, str) {             actionNew();            frame.setTitle("Example - " + title + titleSuffix);            var doc = editor.document;            doc.insertString(0, str, null);        }        // "hello world"        function actionHello() {            showScript(arguments.callee.title,                "alert('Hello, world');");        }        actionHello.title = "Hello, World";        // eval the "hello world"!        function actionEval() {            showScript(actionEval.title,                "eval(\"alert('Hello, world')\");");        }        actionEval.title = "Eval";        // show how to access Java static methods        function actionJavaStatic() {            showScript(arguments.callee.title,                "// Just use Java syntax\n" +                "var props = java.lang.System.getProperties();\n" +                "alert(props.get('os.name'));");        }        actionJavaStatic.title = "Java Static Calls";        // show how to access Java classes, methods        function actionJavaAccess() {

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?