KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > armedbear > j > WebBuffer


1 /*
2  * WebBuffer.java
3  *
4  * Copyright (C) 1998-2003 Peter Graves
5  * $Id: WebBuffer.java,v 1.9 2003/08/13 15:13:51 piso Exp $
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20  */

21
22 package org.armedbear.j;
23
24 import java.awt.AWTEvent JavaDoc;
25 import java.awt.Cursor JavaDoc;
26 import java.awt.Image JavaDoc;
27 import java.awt.Rectangle JavaDoc;
28 import java.awt.event.MouseEvent JavaDoc;
29 import java.io.InputStream JavaDoc;
30 import java.util.Hashtable JavaDoc;
31 import javax.swing.SwingUtilities JavaDoc;
32
33 public final class WebBuffer extends Buffer implements WebConstants
34 {
35     private String JavaDoc ref;
36     private WebHistory history;
37     private Hashtable JavaDoc refs;
38     private String JavaDoc contentType;
39     private String JavaDoc errorText;
40
41     private WebBuffer(File file, File cache, String JavaDoc ref)
42     {
43         super();
44         setFile(file);
45         setCache(cache);
46         this.ref = ref;
47         init();
48     }
49
50     private void init()
51     {
52         initializeUndo();
53         type = TYPE_NORMAL;
54         forceReadOnly = true;
55         mode = Editor.getModeList().getMode(WEB_MODE);
56         formatter = new WebFormatter(this);
57         setInitialized(true);
58     }
59
60     public final WebHistory getHistory()
61     {
62         return history;
63     }
64
65     public final void setHistory(WebHistory history)
66     {
67         this.history = history;
68     }
69
70     public final String JavaDoc getContentType()
71     {
72         return contentType;
73     }
74
75     public final void setContentType(String JavaDoc contentType)
76     {
77         this.contentType = contentType;
78     }
79
80     private int maxChars;
81
82     private final int maxChars()
83     {
84         if (maxChars == 0) {
85             Display display = Editor.currentEditor().getDisplay();
86             int charWidth = display.getCharWidth();
87             if (charWidth > 0)
88                 maxChars = display.getWidth() / charWidth - 2;
89             else
90                 maxChars = 80;
91         }
92         return maxChars;
93     }
94
95     public Position getInitialDotPos()
96     {
97         if (ref != null) {
98             Position pos = findRef(ref);
99             if (pos != null)
100                 return pos;
101         }
102         return new Position(getFirstLine(), 0);
103     }
104
105     public static void browse(Editor editor, File file, String JavaDoc ref)
106     {
107         if (file == null)
108             return;
109         Buffer buf = null;
110         // Look for existing buffer.
111
for (BufferIterator it = new BufferIterator(); it.hasNext();) {
112             Buffer b = it.nextBuffer();
113             if (b instanceof WebBuffer && b.getFile().equals(file)) {
114                 buf = b;
115                 break;
116             }
117         }
118         if (buf == null)
119             buf = createWebBuffer(file, null, ref);
120         editor.makeNext(buf);
121         editor.switchToBuffer(buf);
122     }
123
124     public static WebBuffer createWebBuffer(File file, File cache, String JavaDoc ref)
125     {
126         return new WebBuffer(file, cache, ref);
127     }
128
129     public Position findRef(String JavaDoc ref)
130     {
131         if (ref != null && refs != null) {
132             Object JavaDoc obj = refs.get(ref);
133             if (obj instanceof Integer JavaDoc) {
134                 Position pos = getPosition(((Integer JavaDoc) obj).intValue());
135                 if (pos != null)
136                     pos.skipWhitespace();
137                 return pos;
138             }
139         }
140         return null;
141     }
142
143     public static void viewPage()
144     {
145         final Editor editor = Editor.currentEditor();
146         if (editor.getModeId() != HTML_MODE)
147             return;
148         final Buffer buffer = editor.getBuffer();
149         File file = buffer.getFile();
150         if (file == null)
151             return;
152         Buffer buf = null;
153         for (BufferIterator it = new BufferIterator(); it.hasNext();) {
154             Buffer b = it.nextBuffer();
155             if (b instanceof WebBuffer && file.equals(b.getFile())) {
156                 buf = b;
157                 break;
158             }
159         }
160         if (buf == null) {
161             buf = WebBuffer.createWebBuffer(file, buffer.getCache(), null);
162             ((WebBuffer)buf).setContentType("text/html");
163         }
164         editor.makeNext(buf);
165         editor.activate(buf);
166     }
167
168     public static void viewSource()
169     {
170         final Editor editor = Editor.currentEditor();
171         final Buffer buffer = editor.getBuffer();
172         if (!(buffer instanceof WebBuffer))
173             return;
174         final Line dotLine = editor.getDotLine();
175         File file = buffer.getFile();
176         Buffer buf = Editor.getBufferList().findBuffer(file);
177         if (buf == null)
178             buf = Buffer.createBuffer(file, buffer.getCache(), null);
179         if (buf != null) {
180             editor.makeNext(buf);
181             editor.activate(buf);
182             if (dotLine instanceof WebLine) {
183                 int sourceOffset = ((WebLine)dotLine).getSourceOffset();
184                 Position pos = buf.getPosition(sourceOffset);
185                 editor.moveDotTo(pos);
186             }
187         }
188     }
189
190     private boolean empty = true;
191
192     public int load()
193     {
194         if (getFirstLine() == null)
195             setText("");
196         setLoaded(true);
197         go(getFile(), 0, contentType);
198         return LOAD_COMPLETED;
199     }
200
201     protected void loadFile(File localFile)
202     {
203         WebLoader loader = new WebLoader(localFile);
204         LineSequence lines = loader.load();
205         if (lines != null) {
206             try {
207                 lockWrite();
208             }
209             catch (InterruptedException JavaDoc e) {
210                 Log.debug(e);
211                 return;
212             }
213             try {
214                 setFirstLine(lines.getFirstLine());
215                 setLastLine(lines.getLastLine());
216                 renumberOriginal();
217                 empty = false;
218             }
219             finally {
220                 unlockWrite();
221             }
222         }
223         refs = loader.getRefs();
224         final File file = getFile();
225         if (file != null && file.equals(localFile))
226             setLastModified(localFile.lastModified());
227         setLoaded(true);
228     }
229
230     public Cursor JavaDoc getDefaultCursor(Position pos)
231     {
232         if (pos != null && pos.getLine() instanceof WebLine) {
233             HtmlLineSegment segment =
234                 ((WebLine)pos.getLine()).findSegment(pos.getOffset());
235             if (segment != null && segment.getLink() != null)
236                 return Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
237         }
238         return super.getDefaultCursor();
239     }
240
241     public final int getMaximumColumns()
242     {
243         return maxChars();
244     }
245
246     public static void followLink()
247     {
248         followLink(false);
249     }
250
251     public static void mouseFollowLink()
252     {
253         final Editor editor = Editor.currentEditor();
254         // If this method is invoked via a mouse event mapping, move dot to
255
// location of mouse click first.
256
AWTEvent JavaDoc e = editor.getDispatcher().getLastEvent();
257         if (e instanceof MouseEvent JavaDoc)
258             editor.mouseMoveDotToPoint((MouseEvent JavaDoc) e);
259         followLink(true);
260     }
261
262     public static void followLink(boolean exact)
263     {
264         final Editor editor = Editor.currentEditor();
265         final Buffer buffer = editor.getBuffer();
266         if (!(buffer instanceof WebBuffer))
267             return;
268         final WebBuffer wb = (WebBuffer) buffer;
269         if (wb.getFile() == null)
270             return;
271         final Line dotLine = editor.getDotLine();
272         if (!(dotLine instanceof WebLine))
273             return;
274
275         final File historyFile = wb.getFile();
276         final int historyOffset = wb.getAbsoluteOffset(editor.getDot());
277         final String JavaDoc historyContentType = wb.getContentType();
278
279         final int dotOffset = editor.getDotOffset();
280
281         Link link = null;
282         HtmlLineSegment segment = ((WebLine)dotLine).findSegment(dotOffset);
283         if (segment != null)
284             link = segment.getLink();
285         if (link == null) {
286             if (exact)
287                 return;
288             segment = findLink(dotLine, dotOffset);
289             if (segment == null)
290                 return;
291             link = segment.getLink();
292         }
293         if (link == null)
294             return;
295         Debug.assertTrue(link == segment.getLink());
296         final String JavaDoc target = link.getTarget();
297         if (target == null) {
298             Debug.bug("target is null");
299             return;
300         }
301         if (target.startsWith("mailto:")) {
302             MessageDialog.showMessageDialog(editor,
303                 "Sorry, mailto URLs are not yet supported.", "Sorry...");
304             return;
305         }
306
307         int index = target.indexOf('#');
308         if (index == 0) {
309             // It's a fragment identifier referring to a location in the same
310
// buffer.
311
Position pos = wb.findRef(target.substring(1));
312             if (pos != null) {
313                 wb.saveHistory(historyFile, historyOffset, historyContentType);
314                 editor.moveDotTo(pos);
315                 editor.setUpdateFlag(REFRAME);
316             }
317             return;
318         }
319
320         String JavaDoc filename;
321         String JavaDoc ref = null;
322         if (index >= 0) {
323             filename = target.substring(0, index);
324             ref = target.substring(index + 1);
325         } else
326             filename = target;
327
328         final File destination =
329             resolve(wb.getFile().getParentFile(), filename);
330
331         if (destination.equals(wb.getFile())) {
332             Position pos = wb.findRef(ref);
333             if (pos != null) {
334                 wb.saveHistory(historyFile, historyOffset, historyContentType);
335                 editor.moveDotTo(pos);
336             }
337             return;
338         }
339
340         final HtmlLineSegment theSegment = segment;
341         final Link theLink = link;
342         if (destination instanceof HttpFile) {
343             final String JavaDoc theRef = ref;
344             final HttpLoadProcess httpLoadProcess =
345                 new HttpLoadProcess(wb, (HttpFile) destination);
346             Runnable JavaDoc successRunnable = new Runnable JavaDoc() {
347                 public void run()
348                 {
349                     final String JavaDoc contentType = httpLoadProcess.getContentType();
350                     Log.debug("content-type = " + contentType);
351                     boolean isImage = false;
352                     if (contentType != null && contentType.toLowerCase().startsWith("image/"))
353                         isImage = true;
354                     else {
355                         String JavaDoc extension = Utilities.getExtension(destination);
356                         if (extension != null) {
357                             extension = extension.toLowerCase();
358                             if (extension.equals(".jpg") || extension.equals(".gif") || extension.equals(".png"))
359                                 isImage = true;
360                         }
361                     }
362                     if (isImage) {
363                         if (theLink instanceof ImageLink) {
364                             ImageLoader loader = new ImageLoader(httpLoadProcess.getCache());
365                             java.awt.Image JavaDoc image = loader.loadImage();
366                             if (image != null)
367                                 wb.insertImage(editor, dotLine, theSegment, image);
368                         } else {
369                             // Normal link.
370
// BUG!! This isn't right either. We should display the image in
371
// the current buffer.
372
ImageBuffer buf = ImageBuffer.createImageBuffer(destination, httpLoadProcess.getCache(), null);
373                             editor.makeNext(buf);
374                             editor.activate(buf);
375                             editor.updateDisplay();
376                         }
377                         return;
378                     }
379                     if (wb.loadLocalFile(httpLoadProcess.getCache(), contentType, httpLoadProcess.getCache().getEncoding())) {
380                         wb.saveHistory(historyFile, historyOffset, historyContentType);
381                         wb.setFile(httpLoadProcess.getFile());
382                         wb.setCache(httpLoadProcess.getCache());
383                         Position pos = null;
384                         if (theRef != null)
385                             pos = wb.findRef(theRef);
386                         if (pos == null)
387                             pos = new Position(wb.getFirstLine(), 0);
388                         wb.update(pos);
389                     }
390                     for (EditorIterator it = new EditorIterator(); it.hasNext();) {
391                         Editor ed = it.nextEditor();
392                         if (ed != null && ed.getBuffer() == wb)
393                             ed.setDefaultCursor();
394                     }
395                 }
396             };
397             ErrorRunnable errorRunnable = new ErrorRunnable("Operation failed") {
398                 public void run()
399                 {
400                     Log.debug("followLink errorRunnable.run");
401                     String JavaDoc errorText = httpLoadProcess.getErrorText();
402                     if (errorText == null || errorText.length() == 0)
403                         errorText = "Unable to load " + destination.netPath();
404                     setMessage(errorText);
405                     super.run();
406                 }
407             };
408             httpLoadProcess.setSuccessRunnable(successRunnable);
409             httpLoadProcess.setErrorRunnable(errorRunnable);
410             httpLoadProcess.setProgressNotifier(new StatusBarProgressNotifier(wb));
411             editor.setWaitCursor();
412             new Thread JavaDoc(httpLoadProcess).start();
413         } else {
414             // Local file.
415
String JavaDoc extension = Utilities.getExtension(destination);
416             if (extension != null) {
417                 extension = extension.toLowerCase();
418                 if (extension.equals(".jpg") || extension.equals(".gif") || extension.equals(".png")) {
419                     if (theLink instanceof ImageLink) {
420                         ImageLoader loader = new ImageLoader(destination);
421                         java.awt.Image JavaDoc image = loader.loadImage();
422                         if (image != null)
423                             wb.insertImage(editor, dotLine, theSegment, image);
424                     } else {
425                         // BUG!! Should display image in same buffer.
426
ImageBuffer buf = ImageBuffer.createImageBuffer(destination, null, null);
427                         editor.makeNext(buf);
428                         editor.activate(buf);
429                         editor.updateDisplay();
430                     }
431                     return;
432                 }
433             }
434             if (wb.loadLocalFile(destination)) {
435                 wb.saveHistory(historyFile, historyOffset, historyContentType);
436                 wb.setFile(destination);
437                 wb.setCache(null);
438                 Position pos = null;
439                 if (ref != null)
440                     pos = wb.findRef(ref);
441                 if (pos == null)
442                     pos = new Position(wb.getFirstLine(), 0);
443                 wb.update(pos);
444             }
445         }
446     }
447
448     public static HtmlLineSegment findLink(Line line, int offset)
449     {
450         HtmlLineSegment segment = null;
451         if (line instanceof WebLine) {
452             LineSegmentList segmentList = ((WebLine)line).getSegmentList();
453             if (segmentList != null) {
454                 int where = 0;
455                 final int size = segmentList.size();
456                 for (int i = 0; i < size; i++) {
457                     HtmlLineSegment seg =
458                         (HtmlLineSegment) segmentList.getSegment(i);
459                     if (seg.getLink() != null) {
460                         if (segment == null || where < offset)
461                             segment = seg;
462                     }
463                     where += seg.length();
464                     if (where > offset && segment != null)
465                         break;
466                 }
467             }
468         }
469         return segment;
470     }
471
472     private static File resolve(File base, String JavaDoc fileName)
473     {
474         while (fileName.startsWith("../")) {
475             File parent = base.getParentFile();
476             if (parent != null) {
477                 base = parent;
478                 fileName = fileName.substring(3);
479             } else
480                 break;
481         }
482         // Strip any remaining (i.e. bogus) lead dots.
483
while (fileName.startsWith("../")) {
484             fileName = fileName.substring(3);
485         }
486         return File.getInstance(base, fileName);
487     }
488
489     // BUG!! Optimize this - containsImageLine flag
490
public int getDisplayHeight()
491     {
492         int height = 0;
493         for (Line line = getFirstLine(); line != null; line = line.nextVisible())
494             height += line.getHeight();
495         return height;
496     }
497
498     private void insertImage(final Editor editor, final Line line,
499         final HtmlLineSegment segment, final Image JavaDoc image)
500     {
501         final int imageHeight = image.getHeight(null);
502         if (imageHeight == 0)
503             return;
504
505         LineSegmentList segments = ((WebLine)line).getSegmentList();
506         segments.removeSegment(segment);
507
508         // Force next call to line.getText() to enumerate the segments again.
509
line.setText(null);
510
511         Line before;
512         if (line.isBlank() && line.previous() != null) {
513             // Current line is blank. Put image in its place.
514
before = line.previous();
515         } else {
516             // Put image after current line.
517
before = line;
518         }
519
520         final int lineHeight = new TextLine("").getHeight();
521         final int imageWidth = image.getWidth(null);
522         Line dotLine = null;
523         for (int y = 0; y < imageHeight; y += lineHeight) {
524             Rectangle JavaDoc r = new Rectangle JavaDoc(0, y, imageWidth,
525                 Math.min(lineHeight, imageHeight - y));
526             ImageLine imageLine = new ImageLine(image, r);
527             imageLine.insertAfter(before);
528             before = imageLine;
529             if (dotLine == null)
530                 dotLine = imageLine;
531         }
532         renumber();
533         Debug.assertTrue(dotLine != null);
534         for (EditorIterator it = new EditorIterator(); it.hasNext();) {
535             Editor ed = it.nextEditor();
536             if (ed.getBuffer() == this) {
537                 ed.getDot().moveTo(dotLine, 0);
538                 ed.setMark(null); // Enforce sanity.
539
ed.setUpdateFlag(REFRAME | REPAINT);
540                 ed.updateDisplay();
541             }
542         }
543     }
544
545     public void saveHistory(File historyFile, int historyOffset,
546         String JavaDoc historyContentType)
547     {
548         if (history == null)
549             history = new WebHistory();
550         else
551             history.truncate();
552         history.append(historyFile, historyOffset, historyContentType);
553         history.reset();
554     }
555
556     private boolean loadLocalFile(File localFile)
557     {
558         return loadLocalFile(localFile, "text/html");
559     }
560
561     private boolean loadLocalFile(File localFile, String JavaDoc contentType)
562     {
563         return loadLocalFile(localFile, contentType, null);
564     }
565
566     private boolean loadLocalFile(File localFile, String JavaDoc contentType,
567         String JavaDoc encoding)
568     {
569         // Look for Unicode byte order mark. If we find it, use it to
570
// determine the encoding.
571
InputStream JavaDoc inputStream;
572         try {
573             inputStream = localFile.getInputStream();
574         }
575         catch (Exception JavaDoc e) {
576             Log.error(e);
577             errorText = "File not found";
578             return false; // File not found.
579
}
580         byte[] buf = new byte[2];
581         try {
582             int bytesRead = inputStream.read(buf);
583             inputStream.close();
584             if (bytesRead == 2) {
585                 byte byte1 = buf[0];
586                 byte byte2 = buf[1];
587                 if (byte1 == (byte) 0xfe && byte2 == (byte) 0xff)
588                     encoding = "UnicodeBig";
589                 else if (byte1 == (byte) 0xff && byte2 == (byte) 0xfe)
590                     encoding = "UnicodeLittle";
591             }
592         }
593         catch (Exception JavaDoc e) {
594             Log.error(e);
595             return false;
596         }
597         try {
598             inputStream = localFile.getInputStream();
599         }
600         catch (Exception JavaDoc e) {
601             Log.error(e);
602             errorText = "File not found";
603             return false; // File not found.
604
}
605         boolean isHtml = false;
606         if (contentType != null) {
607             if (contentType.toLowerCase().startsWith("text/html"))
608                 isHtml = true;
609         } else {
610             if (Editor.getModeList().modeAccepts(HTML_MODE, localFile.getName()))
611                 isHtml = true;
612         }
613         try {
614             lockWrite();
615         }
616         catch (InterruptedException JavaDoc e) {
617             Log.debug(e);
618             return false;
619         }
620         try {
621             empty();
622             if (isHtml) {
623                 loadFile(localFile);
624                 setContentType(contentType);
625                 setFormatter(new WebFormatter(this));
626             } else {
627                 super.load(inputStream, encoding);
628                 if (getFirstLine() == null) {
629                     // New or 0-byte file.
630
appendLine("");
631                     lineSeparator = System.getProperty("line.separator");
632                 }
633                 renumberOriginal();
634                 setContentType(contentType);
635                 Mode mode = Editor.getModeList().getModeForContentType(contentType);
636                 if (mode == null) {
637                     File file = getFile();
638                     if (file != null)
639                         mode = Editor.getModeList().getModeForFileName(file.getName());
640                 }
641                 if (mode != null) {
642                     setFormatter(mode.getFormatter(this));
643                     formatter.parseBuffer();
644                 } else
645                     setFormatter(new PlainTextFormatter(this));
646             }
647         }
648         finally {
649             unlockWrite();
650         }
651         return true;
652     }
653
654     public static void back()
655     {
656         final Editor editor = Editor.currentEditor();
657         final Buffer buffer = editor.getBuffer();
658         if (!(buffer instanceof WebBuffer))
659             return;
660         final WebBuffer wb = (WebBuffer) buffer;
661         WebHistory history = wb.getHistory();
662         if (history == null)
663             return;
664         boolean atEnd = history.atEnd();
665         WebHistoryEntry current = history.getCurrent();
666         WebHistoryEntry previous = history.getPrevious();
667         if (previous != null) {
668             if (atEnd)
669                 history.append(wb.getFile(),
670                     wb.getAbsoluteOffset(editor.getDot()), wb.getContentType());
671             else if (current != null)
672                 current.setOffset(wb.getAbsoluteOffset(editor.getDot()));
673             else
674                 Debug.bug();
675             if (previous.getFile().equals(wb.getFile()))
676                 wb.update(previous.getOffset());
677             else
678                 wb.go(previous.getFile(), previous.getOffset(), previous.getContentType());
679         }
680     }
681
682     public static void forward()
683     {
684         final Editor editor = Editor.currentEditor();
685         final Buffer buffer = editor.getBuffer();
686         if (!(buffer instanceof WebBuffer))
687             return;
688         final WebBuffer wb = (WebBuffer) buffer;
689         WebHistory history = wb.getHistory();
690         if (history == null)
691             return;
692         WebHistoryEntry current = history.getCurrent();
693         WebHistoryEntry next = history.getNext();
694         if (next != null) {
695             if (current != null)
696                 current.setOffset(wb.getAbsoluteOffset(editor.getDot()));
697             else
698                 Debug.bug();
699             if (next.getFile().equals(wb.getFile()))
700                 wb.update(next.getOffset());
701             else
702                 wb.go(next.getFile(), next.getOffset(), next.getContentType());
703         }
704     }
705
706     public static void refresh()
707     {
708         final Editor editor = Editor.currentEditor();
709         final Buffer buffer = editor.getBuffer();
710         if (buffer instanceof WebBuffer)
711             ((WebBuffer)buffer).reload(editor);
712     }
713
714     private void reload(Editor editor)
715     {
716         final File file = getFile();
717         if (file instanceof HttpFile) {
718             HttpFile httpFile = (HttpFile) file;
719             File cache = httpFile.getCache();
720             if (cache != null) {
721                 if (cache.isFile())
722                     cache.delete();
723                 httpFile.setCache(null);
724             }
725         }
726         int offset = getAbsoluteOffset(editor.getDot());
727         go(file, offset, contentType);
728     }
729
730     public void go(final File destination, final int offset, String JavaDoc contentType)
731     {
732         if (destination == null)
733             return;
734
735         if (destination.isLocal()) {
736             if (loadLocalFile(destination, contentType)) {
737                 setFile(destination);
738                 update(offset);
739                 setLastModified(destination.lastModified());
740             } else {
741                 // Error!
742
Runnable JavaDoc errorRunnable = new Runnable JavaDoc() {
743                     public void run()
744                     {
745                         if (empty && Editor.getBufferList().contains(WebBuffer.this))
746                             kill();
747                         for (EditorIterator it = new EditorIterator(); it.hasNext();) {
748                             Editor ed = it.nextEditor();
749                             if (empty || ed.getBuffer() == WebBuffer.this) {
750                                 ed.updateLocation();
751                                 ed.updateDisplay();
752                             }
753                         }
754                         if (errorText == null)
755                             errorText = "Unable to load " + destination.canonicalPath();
756                         MessageDialog.showMessageDialog(errorText, "Error");
757                     }
758                 };
759                 SwingUtilities.invokeLater(errorRunnable);
760             }
761             return;
762         }
763
764         // Destination is not local.
765
if (destination.equals(getFile())) {
766             File cache = getCache();
767             if (cache != null && cache.isFile()) {
768                 // We have a cache.
769
if (loadLocalFile(cache, contentType)) {
770                     setFile(destination);
771                     update(offset);
772                 }
773                 return;
774             }
775         }
776
777         Debug.assertTrue(destination instanceof HttpFile);
778         final HttpFile httpFile = (HttpFile) destination;
779         File cache = httpFile.getCache();
780         if (cache != null) {
781             if (cache.isFile()) {
782                 if (contentType == null)
783                     contentType = httpFile.getContentType();
784                 if (loadLocalFile(cache, contentType)) {
785                     setFile(destination);
786                     setCache(cache);
787                     update(offset);
788                 }
789                 return;
790             }
791             cache = null;
792             httpFile.setCache(null);
793         }
794
795         Debug.assertTrue(cache == null);
796         Log.debug("go cache is null");
797         final File oldFile = getFile();
798         setFile(destination);
799         final HttpLoadProcess httpLoadProcess = new HttpLoadProcess(this, httpFile);
800         Runnable JavaDoc httpSuccessRunnable = new Runnable JavaDoc() {
801             public void run()
802             {
803                 File localCache = httpLoadProcess.getCache();
804                 if (localCache != null && localCache.isFile()) {
805                     if (loadLocalFile(localCache, httpLoadProcess.getContentType(), localCache.getEncoding())) {
806                         setFile(httpLoadProcess.getFile());
807                         setCache(localCache);
808                         setContentType(httpLoadProcess.getContentType());
809                         update(offset);
810                     }
811                 }
812             }
813         };
814         Runnable JavaDoc httpCancelRunnable = new Runnable JavaDoc() {
815             public void run()
816             {
817                 setFile(oldFile);
818                 setBusy(false);
819                 if (empty && Editor.getBufferList().contains(WebBuffer.this))
820                     kill();
821                 for (EditorIterator it = new EditorIterator(); it.hasNext();) {
822                     Editor ed = it.nextEditor();
823                     if (ed != null && ed.getBuffer() == WebBuffer.this) {
824                         ed.status("Transfer cancelled");
825                         ed.setDefaultCursor();
826                     }
827                 }
828                 Editor.currentEditor().updateDisplay();
829                 MessageDialog.showMessageDialog("Transfer cancelled", httpFile.netPath());
830             }
831         };
832         ErrorRunnable httpErrorRunnable = new ErrorRunnable("Load failed") {
833             public void run()
834             {
835                 setFile(oldFile);
836                 setBusy(false);
837                 if (empty && Editor.getBufferList().contains(WebBuffer.this))
838                     kill();
839                 if (!httpLoadProcess.cancelled()) {
840                     errorText = httpLoadProcess.getErrorText();
841                     if (errorText == null || errorText.length() == 0)
842                         errorText = "Unable to load " + httpFile.netPath();
843                     setMessage(errorText);
844                 }
845                 super.run();
846             }
847         };
848         httpLoadProcess.setSuccessRunnable(httpSuccessRunnable);
849         httpLoadProcess.setCancelRunnable(httpCancelRunnable);
850         httpLoadProcess.setErrorRunnable(httpErrorRunnable);
851         httpLoadProcess.setProgressNotifier(new StatusBarProgressNotifier(WebBuffer.this));
852         httpLoadProcess.start();
853     }
854
855     private void update(int offset)
856     {
857         Position pos = getPosition(offset);
858         if (pos == null)
859             pos = new Position(getFirstLine(), 0);
860         setBusy(false);
861         update(pos);
862     }
863
864     private void update(Position pos)
865     {
866         for (EditorIterator it = new EditorIterator(); it.hasNext();) {
867             Editor ed = it.nextEditor();
868             if (ed.getBuffer() == this) {
869                 ed.setDot(pos.copy());
870                 ed.setMark(null);
871                 ed.moveCaretToDotCol();
872                 ed.setTopLine(getFirstLine());
873                 ed.setUpdateFlag(REFRAME);
874                 ed.repaintDisplay();
875                 ed.updateDisplay();
876                 ed.updateLocation();
877             }
878         }
879         Sidebar.setUpdateFlagInAllFrames(SIDEBAR_BUFFER_LIST_CHANGED);
880         Sidebar.repaintBufferListInAllFrames();
881         Editor.currentEditor().status("Loading complete");
882     }
883
884     public boolean isTransient()
885     {
886         if (super.isTransient())
887             return true;
888         File file = getFile();
889         if (file != null && file.isLocal()) {
890             if (file.equals(Help.getBindingsFile()))
891                 return true;
892             File dir = file.getParentFile();
893             if (dir != null && dir.equals(Help.getDocumentationDirectory()))
894                 return true;
895         }
896         return false;
897     }
898
899     public boolean save()
900     {
901         // We shouldn't be trying to save a WebBuffer.
902
Debug.bug();
903         return true;
904     }
905
906     public static void copyLink()
907     {
908         final Editor editor = Editor.currentEditor();
909         final Buffer buffer = editor.getBuffer();
910         if (buffer instanceof WebBuffer) {
911             Position pos = editor.getDot();
912             if (pos != null && pos.getLine() instanceof WebLine) {
913                 HtmlLineSegment segment =
914                     ((WebLine)pos.getLine()).findSegment(pos.getOffset());
915                 if (segment != null) {
916                     Link link = segment.getLink();
917                     if (link == null)
918                         return;
919                     String JavaDoc copy = null;
920                     String JavaDoc target = link.getTarget();
921                     if (target == null)
922                         return;
923                     if (target.startsWith("mailto:")) {
924                         copy = target;
925                     } else {
926                         int index = target.indexOf('#');
927                         String JavaDoc filename;
928                         String JavaDoc ref = null;
929                         if (index == 0) {
930                             filename = buffer.getFile().netPath();
931                             ref = target;
932                         } else if (index > 0) {
933                             filename = target.substring(0, index);
934                             ref = target.substring(index);
935                         } else
936                             filename = target;
937                         final File destination =
938                             resolve(buffer.getFile().getParentFile(),
939                                 filename);
940                         if (destination != null) {
941                             copy = destination.netPath();
942                             if (ref != null)
943                                 copy = copy.concat(ref);
944                         }
945                     }
946                     if (copy != null) {
947                         KillRing killRing = editor.getKillRing();
948                         killRing.appendNew(copy);
949                         killRing.copyLastKillToSystemClipboard();
950                         editor.status("Link copied to clipboard");
951                     }
952                 }
953             }
954         }
955     }
956 }
957
Popular Tags