KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sf > jftp > gui > base > LocalDir


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

16 package net.sf.jftp.gui.base;
17
18 import java.awt.BorderLayout JavaDoc;
19 import java.awt.Cursor JavaDoc;
20 import java.awt.FlowLayout JavaDoc;
21 import java.awt.Insets JavaDoc;
22 import java.awt.event.ActionEvent JavaDoc;
23 import java.awt.event.ActionListener JavaDoc;
24 import java.awt.event.KeyEvent JavaDoc;
25 import java.awt.event.KeyListener JavaDoc;
26 import java.awt.event.MouseAdapter JavaDoc;
27 import java.awt.event.MouseEvent JavaDoc;
28 import java.awt.event.MouseListener JavaDoc;
29 import java.io.BufferedInputStream JavaDoc;
30 import java.io.BufferedOutputStream JavaDoc;
31 import java.io.File JavaDoc;
32 import java.io.FileInputStream JavaDoc;
33 import java.io.FileOutputStream JavaDoc;
34 import java.io.IOException JavaDoc;
35 import java.io.StreamTokenizer JavaDoc;
36 import java.util.Date JavaDoc;
37 import java.util.Enumeration JavaDoc;
38 import java.util.Hashtable JavaDoc;
39 import java.util.zip.ZipEntry JavaDoc;
40 import java.util.zip.ZipFile JavaDoc;
41
42 import javax.swing.DefaultListModel JavaDoc;
43 import javax.swing.ImageIcon JavaDoc;
44 import javax.swing.JComboBox JavaDoc;
45 import javax.swing.JEditorPane JavaDoc;
46 import javax.swing.JLabel JavaDoc;
47 import javax.swing.JList JavaDoc;
48 import javax.swing.JMenuItem JavaDoc;
49 import javax.swing.JOptionPane JavaDoc;
50 import javax.swing.JPanel JavaDoc;
51 import javax.swing.JPopupMenu JavaDoc;
52 import javax.swing.JScrollPane JavaDoc;
53 import javax.swing.JToolBar JavaDoc;
54 import javax.swing.SwingUtilities JavaDoc;
55 import javax.swing.event.ListSelectionEvent JavaDoc;
56 import javax.swing.event.ListSelectionListener JavaDoc;
57
58 import net.sf.jftp.JFtp;
59 import net.sf.jftp.config.SaveSet;
60 import net.sf.jftp.config.Settings;
61 import net.sf.jftp.gui.base.dir.DirCanvas;
62 import net.sf.jftp.gui.base.dir.DirCellRenderer;
63 import net.sf.jftp.gui.base.dir.DirComponent;
64 import net.sf.jftp.gui.base.dir.DirEntry;
65 import net.sf.jftp.gui.base.dir.DirLister;
66 import net.sf.jftp.gui.base.dir.DirPanel;
67 import net.sf.jftp.gui.base.dir.TableUtils;
68 import net.sf.jftp.gui.framework.HImage;
69 import net.sf.jftp.gui.framework.HImageButton;
70 import net.sf.jftp.gui.framework.HPanel;
71 import net.sf.jftp.gui.tasks.Creator;
72 import net.sf.jftp.gui.tasks.ImageViewer;
73 import net.sf.jftp.gui.tasks.NameChooser;
74 import net.sf.jftp.gui.tasks.RemoteCommand;
75 import net.sf.jftp.net.BasicConnection;
76 import net.sf.jftp.net.ConnectionListener;
77 import net.sf.jftp.net.FilesystemConnection;
78 import net.sf.jftp.net.FtpConnection;
79 import net.sf.jftp.net.SmbConnection;
80 import net.sf.jftp.system.LocalIO;
81 import net.sf.jftp.system.StringUtils;
82 import net.sf.jftp.system.UpdateDaemon;
83 import net.sf.jftp.system.logging.Log;
84 import net.sf.jftp.util.ZipFileCreator;
85
86
87 public class LocalDir extends DirComponent implements ListSelectionListener JavaDoc,
88                                                   ActionListener JavaDoc,
89                                                   ConnectionListener,
90                                                   KeyListener JavaDoc
91 {
92     static final String JavaDoc deleteString = "rm";
93     static final String JavaDoc mkdirString = "mkdir";
94     static final String JavaDoc refreshString = "fresh";
95     static final String JavaDoc cdString = "cd";
96     static final String JavaDoc cmdString = "cmd";
97     static final String JavaDoc downloadString = "<-";
98     static final String JavaDoc uploadString = "->";
99     static final String JavaDoc zipString = "zip";
100     static final String JavaDoc cpString = "cp";
101     static final String JavaDoc rnString = "rn";
102     static final String JavaDoc cdUpString = "cdUp";
103     HImageButton deleteButton;
104     HImageButton mkdirButton;
105     HImageButton cmdButton;
106     HImageButton refreshButton;
107     HImageButton cdButton;
108     HImageButton uploadButton;
109     HImageButton zipButton;
110     HImageButton cpButton;
111     HImageButton rnButton;
112     private DirCanvas label = new DirCanvas(this);
113     private boolean pathChanged = true;
114     private boolean firstGui = true;
115     private int pos = 0;
116     private JPanel JavaDoc p = new JPanel JavaDoc();
117     private JToolBar JavaDoc buttonPanel = new JToolBar JavaDoc()
118     {
119         public Insets JavaDoc getInsets()
120         {
121             return new Insets JavaDoc(0, 0, 0, 0);
122         }
123     };
124
125     private JToolBar JavaDoc currDirPanel = new JToolBar JavaDoc()
126     {
127         public Insets JavaDoc getInsets()
128         {
129             return new Insets JavaDoc(0, 0, 0, 0);
130         }
131     };
132
133     private DefaultListModel JavaDoc jlm;
134     private JScrollPane JavaDoc jsp = new JScrollPane JavaDoc(jl);
135     private int tmpindex = -1;
136     private Hashtable JavaDoc dummy = new Hashtable JavaDoc();
137     private JPopupMenu JavaDoc popupMenu = new JPopupMenu JavaDoc();
138     private JMenuItem JavaDoc runFile = new JMenuItem JavaDoc("Launch file");
139     private JMenuItem JavaDoc viewFile = new JMenuItem JavaDoc("View file");
140     private JMenuItem JavaDoc props = new JMenuItem JavaDoc("Properties");
141     private DirEntry currentPopup = null;
142     private String JavaDoc sortMode = null;
143     String JavaDoc[] sortTypes = new String JavaDoc[] { "Normal", "Reverse", "Size", "Size/Re" };
144     private JComboBox JavaDoc sorter = new JComboBox JavaDoc(sortTypes);
145     HImageButton cdUpButton;
146     private boolean dateEnabled = false;
147
148     /**
149     * LocalDir constructor.
150     */

151     public LocalDir()
152     {
153         type = "local";
154         con = new FilesystemConnection();
155         con.addConnectionListener(this);
156     }
157
158     /**
159     * LocalDir constructor.
160     */

161     public LocalDir(String JavaDoc path)
162     {
163         type = "local";
164         this.path = path;
165         con = new FilesystemConnection();
166         con.addConnectionListener(this);
167         con.chdir(path);
168
169         //gui(false);
170
}
171
172     /**
173     * Creates the gui and adds the MouseListener etc.
174     */

175     public void gui_init()
176     {
177         setLayout(new BorderLayout JavaDoc());
178         currDirPanel.setFloatable(false);
179         buttonPanel.setFloatable(false);
180
181         FlowLayout JavaDoc f = new FlowLayout JavaDoc(FlowLayout.RIGHT);
182         f.setHgap(1);
183         f.setVgap(2);
184
185         buttonPanel.setLayout(f);
186         buttonPanel.setMargin(new Insets JavaDoc(0, 0, 0, 0));
187
188         runFile.addActionListener(this);
189         viewFile.addActionListener(this);
190         props.addActionListener(this);
191         popupMenu.add(runFile);
192         popupMenu.add(viewFile);
193         popupMenu.add(props);
194
195         deleteButton = new HImageButton(Settings.deleteImage, deleteString,
196                                         "Delete selected", this);
197         deleteButton.setToolTipText("Delete selected");
198
199         mkdirButton = new HImageButton(Settings.mkdirImage, mkdirString,
200                                        "Create a new directory", this);
201         mkdirButton.setToolTipText("Create directory");
202
203         refreshButton = new HImageButton(Settings.refreshImage, refreshString,
204                                          "Refresh current directory", this);
205         refreshButton.setToolTipText("Refresh directory");
206         refreshButton.setRolloverIcon(new ImageIcon JavaDoc(HImage.getImage(this, Settings.refreshImage2)));
207         refreshButton.setRolloverEnabled(true);
208
209         cdButton = new HImageButton(Settings.cdImage, cdString,
210                                     "Change directory", this);
211         cdButton.setToolTipText("Change directory");
212
213         uploadButton = new HImageButton(Settings.uploadImage, uploadString,
214                                         "Upload selected", this);
215         uploadButton.setToolTipText("Upload selected");
216
217         zipButton = new HImageButton(Settings.zipFileImage, zipString,
218                                      "Add selected to new zip file", this);
219         zipButton.setToolTipText("Create zip");
220
221         cpButton = new HImageButton(Settings.copyImage, cpString,
222                                     "Copy selected files to another local dir",
223                                     this);
224         cpButton.setToolTipText("Local copy selected");
225
226         rnButton = new HImageButton(Settings.textFileImage, rnString,
227                                     "Rename selected file or directory", this);
228         rnButton.setToolTipText("Rename selected");
229
230         cdUpButton = new HImageButton(Settings.cdUpImage, cdUpString,
231                                       "Go to Parent Directory", this);
232         cdUpButton.setToolTipText("Go to Parent Directory");
233
234         label.setText("Filesystem: " + StringUtils.cutPath(path));
235         label.setSize(getSize().width - 10, 24);
236         currDirPanel.add(label);
237         currDirPanel.setSize(getSize().width - 10, 32);
238         label.setSize(getSize().width - 20, 24);
239
240         p.setLayout(new BorderLayout JavaDoc());
241         p.add("North", currDirPanel);
242
243         buttonPanel.add(sorter);
244
245         buttonPanel.add(new JLabel JavaDoc(" "));
246
247         buttonPanel.add(refreshButton);
248         buttonPanel.add(new JLabel JavaDoc(" "));
249
250         buttonPanel.add(cpButton);
251         buttonPanel.add(rnButton);
252         buttonPanel.add(mkdirButton);
253
254         buttonPanel.add(cdButton);
255         buttonPanel.add(deleteButton);
256         buttonPanel.add(cdUpButton);
257         buttonPanel.add(new JLabel JavaDoc(" "));
258
259         buttonPanel.add(zipButton);
260         buttonPanel.add(new JLabel JavaDoc(" "));
261
262         buttonPanel.add(uploadButton);
263
264         buttonPanel.setVisible(true);
265
266         buttonPanel.setSize(getSize().width - 10, 32);
267
268         //JPanel sortPanel = new JPanel();
269
p.add("East", buttonPanel);
270
271         //p.add("West", sortPanel);
272
sorter.addActionListener(this);
273
274         add("North", p);
275
276         setDirList(true);
277         jlm = new DefaultListModel JavaDoc();
278         jl = new JList JavaDoc(jlm);
279         jl.setCellRenderer(new DirCellRenderer());
280         jl.setVisibleRowCount(Settings.visibleFileRows);
281
282
283         // add this becaus we need to fetch only doubleclicks
284
MouseListener JavaDoc mouseListener = new MouseAdapter JavaDoc()
285         {
286             public void mousePressed(MouseEvent JavaDoc e)
287             {
288                 if(JFtp.uiBlocked)
289                 {
290                     return;
291                 }
292
293                 if(e.isPopupTrigger() || SwingUtilities.isRightMouseButton(e))
294                 {
295                     int index = jl.getSelectedIndex() - 1;
296
297                     if(index < -1)
298                     {
299                         return;
300                     }
301
302                     String JavaDoc tgt = (String JavaDoc) jl.getSelectedValue().toString();
303
304                     if(index < 0)
305                     {
306                     }
307                     else if((dirEntry == null) || (dirEntry.length < index) ||
308                                 (dirEntry[index] == null))
309                     {
310                         return;
311                     }
312                     else
313                     {
314                         currentPopup = dirEntry[index];
315                         popupMenu.show(e.getComponent(), e.getX(), e.getY());
316                     }
317                 }
318             }
319
320             public void mouseClicked(MouseEvent JavaDoc e)
321             {
322                 if(JFtp.uiBlocked)
323                 {
324                     return;
325                 }
326                 
327                 if(Settings.getUseJTableLayout()) {
328                     TableUtils.copyTableSelectionsToJList(jl, table);
329                 }
330
331                 //System.out.println("DirEntryListener::");
332
if(e.getClickCount() == 2)
333                 {
334                     //System.out.println("2xList selection: "+jl.getSelectedValue().toString());
335
int index = jl.getSelectedIndex() - 1;
336
337                     // mousewheel bugfix, ui refresh bugfix
338
if(index < -1)
339                     {
340                         return;
341                     }
342
343                     String JavaDoc tgt = (String JavaDoc) jl.getSelectedValue().toString();
344
345                     //System.out.println("List selection: "+index);
346
if(index < 0)
347                     {
348                         chdir(path + tgt);
349                     }
350                     else if((dirEntry == null) || (dirEntry.length < index) ||
351                                 (dirEntry[index] == null))
352                     {
353                         return;
354                     }
355                     else if(dirEntry[index].isDirectory())
356                     {
357                         if(JFtp.mainFrame != null)
358                         {
359                             JFtp.mainFrame.setCursor(Cursor.WAIT_CURSOR);
360                         }
361
362                         chdir(path + tgt);
363
364                         if(JFtp.mainFrame != null)
365                         {
366                             JFtp.mainFrame.setCursor(Cursor.DEFAULT_CURSOR);
367                         }
368                     }
369                     else
370                     {
371                         showContentWindow(path + dirEntry[index].toString(),
372                                           dirEntry[index]);
373
374                         //blockedTransfer(index);
375
}
376                 }
377             }
378         };
379
380
381         if(Settings.newTableGui) {
382             jsp = new JScrollPane JavaDoc(table);
383             table.getSelectionModel().addListSelectionListener(this);
384             table.addMouseListener(mouseListener);
385         }
386         else {
387             jsp = new JScrollPane JavaDoc(jl);
388             jl.addListSelectionListener(this);
389             jl.addKeyListener(this);
390             jl.addMouseListener(mouseListener);
391
392             jl.requestFocus();
393         }
394         
395         jsp.setSize(getSize().width - 20, getSize().height - 72);
396         add("Center", jsp);
397         jsp.setVisible(true);
398         
399         TableUtils.tryToEnableRowSorting(table);
400         
401         if(Settings.IS_JAVA_1_6) {
402             //sorter.setVisible(false);
403
buttonPanel.remove(sorter);
404         }
405         
406         setVisible(true);
407     }
408
409     public void setViewPort()
410     {
411     }
412
413     /**
414     * Part of a gui refresh.
415     * There's no need to call this by hand.
416     */

417     public void gui(boolean fakeInit)
418     {
419         if(firstGui)
420         {
421             gui_init();
422             firstGui = false;
423         }
424
425         if(con instanceof FilesystemConnection)
426         {
427             label.setText("Filesystem: " + StringUtils.cutPath(path));
428         }
429         else
430         {
431             label.setText("Remote: " + StringUtils.cutPath(path));
432         }
433
434         if(!fakeInit)
435         {
436             setDirList(false);
437         }
438
439         invalidate();
440         validate();
441     }
442
443     /**
444     * List directory and create/update the whole file list.
445     * There's no need to call this by hand.
446     */

447     public void setDirList(boolean fakeInit)
448     {
449         jlm = new DefaultListModel JavaDoc();
450
451         DirEntry dwn = new DirEntry("..", this);
452         dwn.setDirectory();
453         jlm.addElement(dwn);
454
455         if(!fakeInit)
456         {
457             if(pathChanged)
458             {
459                 pathChanged = false;
460
461                 DirLister dir = new DirLister(con, sortMode, Settings.getHideLocalDotNames());
462
463                 while(!dir.finished)
464                 {
465                     LocalIO.pause(10);
466                 }
467
468                 if(dir.isOk())
469                 {
470                     length = dir.getLength();
471                     dirEntry = new DirEntry[length];
472                     files = dir.list();
473
474                     String JavaDoc[] fSize = dir.sList();
475                     int[] perms = dir.getPermissions();
476
477                     // --------- sorting aphabetically ------------
478
// is now in DirLister
479

480                     /*
481                                         if(Settings.sortDir)
482                                         {
483                                             String[] tmpx = new String[length];
484
485                                             //if(fSize != null) System.out.println(":"+length+":"+fSize.length+":"+files.length);
486                                             int pLength = length;
487
488                                             if(perms != null)
489                                             {
490                                                 pLength = perms.length;
491                                             }
492
493                                             //System.out.println(files.length + ":" + fSize.length+":"+ pLength + ":"+ length);
494                                             if((fSize.length != files.length) ||
495                                                    (pLength != files.length) ||
496                                                    (length != files.length))
497                                             {
498                                                 System.out.println("Sort mismatch - hopefully ignoring it...");
499                                             }
500
501                                             for(int x = 0; x < length; x++)
502                                             {
503                                                 if(perms != null)
504                                                 {
505                                                     tmpx[x] = files[x] + "@@@" + fSize[x] + "@@@" +
506                                                               perms[x];
507                                                 }
508                                                 else
509                                                 {
510                                                     tmpx[x] = files[x] + "@@@" + fSize[x];
511                                                 }
512                                             }
513
514                                             LocalIO.sortStrings(tmpx);
515
516                                             for(int y = 0; y < length; y++)
517                                             {
518                                                 files[y] = tmpx[y].substring(0,
519                                                                              tmpx[y].indexOf("@@@"));
520
521                                                 String tmp = tmpx[y].substring(tmpx[y].indexOf("@@@") +
522                                                                                3);
523                                                 fSize[y] = tmp.substring(0, tmp.lastIndexOf("@@@"));
524
525                                                 if(perms != null)
526                                                 {
527                                                     perms[y] = Integer.parseInt(tmpx[y].substring(tmpx[y].lastIndexOf("@@@") +
528                                                                                                   3));
529                                                 }
530                                             }
531                                         }
532                     */

533
534                     // ----------- end sorting --------------------
535
for(int i = 0; i < length; i++)
536                     {
537                         if((files == null) || (files[i] == null))
538                         {
539                             //System.out.println("Critical error, files or files[i] is null!\nPlease report when and how this happened...");
540
System.out.println("skipping setDirList, files or files[i] is null!");
541
542                             return;
543
544                             //System.exit(0);
545
}
546
547                         dirEntry[i] = new DirEntry(files[i], this);
548
549                         if(dirEntry[i] == null)
550                         {
551                             System.out.println("\nskipping setDirList, dirEntry[i] is null!");
552
553                             return;
554                         }
555
556                         if(dirEntry[i].file == null)
557                         {
558                             System.out.println("\nskipping setDirList, dirEntry[i].file is null!");
559
560                             return;
561                         }
562
563                         if(perms != null)
564                         {
565                             dirEntry[i].setPermission(perms[i]);
566                         }
567
568                         if(fSize[i].startsWith("@"))
569                         {
570                             fSize[i] = fSize[i].substring(1);
571                         }
572
573                         dirEntry[i].setFileSize(Long.parseLong(fSize[i]));
574
575                         if(dirEntry[i].file.endsWith("/"))
576                         {
577                             dirEntry[i].setDirectory();
578                         }
579                         else
580                         {
581                             dirEntry[i].setFile();
582                         }
583
584                         //------ date parser -------
585
Object JavaDoc[] d = dir.getDates();
586
587                         if(d != null)
588                         {
589                             dirEntry[i].setDate((Date JavaDoc) d[i]);
590                         }
591
592                         //--------------------------
593
jlm.addElement(dirEntry[i]);
594                     }
595                 }
596                 else
597                 {
598                     Log.debug("Not a directory: " + path);
599                 }
600             }
601
602             //System.out.println("length: "+dirEntry.length);
603
}
604
605         jl.setModel(jlm);
606         
607         update();
608     }
609
610     // 20011213:rb - Added logic for MSDOS style root dir
611

612     /**
613     * Change the directory of this connection and update the gui
614     */

615     public boolean chdir(String JavaDoc p)
616     {
617         if((JFtp.remoteDir == null) || (p == null) || p.trim().equals(""))
618         {
619             return false;
620         }
621
622         BasicConnection c = JFtp.remoteDir.getCon();
623
624         if((c != null) && (c instanceof FtpConnection))
625         {
626             FtpConnection con = (FtpConnection) c;
627
628             //con.setLocalPath(path);
629
SaveSet s = new SaveSet(Settings.login_def, con.getHost(),
630                                     con.getUsername(), con.getPassword(),
631                                     Integer.toString(con.getPort()),
632                                     con.getCachedPWD(), con.getLocalPath());
633         }
634
635         if(con.chdirNoRefresh(p))
636         {
637             path = con.getPWD();
638
639             if(con instanceof FilesystemConnection)
640             {
641                 JFtp.remoteDir.getCon().setLocalPath(path);
642
643                 //con.fireDirectoryUpdate(con);
644
//OR
645
setDate();
646             }
647
648             pathChanged = true;
649             gui(false);
650
651             return true;
652         }
653
654         //Log.debug("CWD (local) : " + p);
655
return false;
656     }
657
658     /**
659     * Handles the user events if the ui is unlocked
660     */

661     public void actionPerformed(ActionEvent JavaDoc e)
662     {
663         if(JFtp.uiBlocked)
664         {
665             return;
666         }
667
668         if(e.getActionCommand().equals("rm"))
669         {
670             lock(false);
671
672             if(Settings.getAskToDelete())
673             {
674                 if(!UITool.askToDelete(this))
675                 {
676                     unlock(false);
677
678                     return;
679                 }
680             }
681
682             for(int i = 0; i < length; i++)
683             {
684                 if(dirEntry[i].selected)
685                 {
686                     con.removeFileOrDir(dirEntry[i].file);
687                 }
688             }
689
690             unlock(false);
691             fresh();
692         }
693         else if(e.getActionCommand().equals("mkdir"))
694         {
695             Creator c = new Creator("Create:", con);
696
697             //fresh();
698
}
699         else if(e.getActionCommand().equals("cmd"))
700         {
701             RemoteCommand rc = new RemoteCommand();
702
703             //fresh();
704
}
705         else if(e.getActionCommand().equals("cd"))
706         {
707             String JavaDoc tmp = UITool.getPathFromDialog(path);
708             chdir(tmp);
709         }
710         else if(e.getActionCommand().equals("fresh"))
711         {
712             fresh();
713         }
714         else if(e.getActionCommand().equals("cp"))
715         {
716             Object JavaDoc[] o = jl.getSelectedValues();
717
718             if(o == null)
719             {
720                 return;
721             }
722
723             String JavaDoc tmp = UITool.getPathFromDialog(path);
724
725             if(tmp == null)
726             {
727                 return;
728             }
729
730             if(!tmp.endsWith("/"))
731             {
732                 tmp = tmp + "/";
733             }
734
735             try
736             {
737                 copy(o, path, "", tmp);
738
739                 //fresh();
740
Log.debug("Copy finished...");
741             }
742             catch(Exception JavaDoc ex)
743             {
744                 ex.printStackTrace();
745                 Log.debug("Copy failed!");
746             }
747         }
748         else if(e.getActionCommand().equals("zip"))
749         {
750             try
751             {
752                 Object JavaDoc[] entry = jl.getSelectedValues();
753
754                 if(entry == null)
755                 {
756                     return;
757                 }
758
759                 String JavaDoc[] tmp = new String JavaDoc[entry.length];
760
761                 for(int i = 0; i < tmp.length; i++)
762                 {
763                     tmp[i] = entry[i].toString();
764                 }
765
766                 NameChooser n = new NameChooser();
767                 String JavaDoc name = n.text.getText();
768                 ZipFileCreator z = new ZipFileCreator(tmp, path, name);
769                 fresh();
770             }
771             catch(Exception JavaDoc ex)
772             {
773                 ex.printStackTrace();
774             }
775         }
776         else if(e.getActionCommand().equals("->"))
777         {
778             blockedTransfer(-2);
779         }
780         else if(e.getActionCommand().equals("<-"))
781         {
782             blockedTransfer(-2);
783         }
784         else if(e.getActionCommand().equals("rn"))
785         {
786             Object JavaDoc[] target = jl.getSelectedValues();
787
788             if((target == null) || (target.length == 0))
789             {
790                 Log.debug("No file selected");
791
792                 return;
793             }
794             else if(target.length > 1)
795             {
796                 Log.debug("Too many files selected");
797
798                 return;
799             }
800
801             //Renamer r = new Renamer(target[0].toString(), path);
802
//fresh();
803
String JavaDoc val = JOptionPane.showInternalInputDialog(JFtp.desktop,
804                                                              "Choose a name...");
805
806             if(val != null)
807             {
808                 if(!con.rename(target[0].toString(), val))
809                 {
810                     Log.debug("Rename failed.");
811                 }
812                 else
813                 {
814                     Log.debug("Successfully renamed.");
815                     fresh();
816                 }
817             }
818         }
819         else if(e.getSource() == props)
820         {
821             JFtp.statusP.jftp.clearLog();
822
823             int x = currentPopup.getPermission();
824             String JavaDoc tmp;
825
826             if(x == FtpConnection.R)
827             {
828                 tmp = "read only";
829             }
830             else if(x == FtpConnection.W)
831             {
832                 tmp = "read/write";
833             }
834             else if(x == FtpConnection.DENIED)
835             {
836                 tmp = "denied";
837             }
838             else
839             {
840                 tmp = "undefined";
841             }
842
843             String JavaDoc msg = "File: " + currentPopup.toString() + "\n" + " Size: " +
844                          currentPopup.getFileSize() + " raw size: " +
845                          currentPopup.getRawSize() + "\n" + " Symlink: " +
846                          currentPopup.isLink() + "\n" + " Directory: " +
847                          currentPopup.isDirectory() + "\n" + " Permission: " +
848                          tmp + "\n";
849             Log.debug(msg);
850         }
851         else if(e.getSource() == viewFile)
852         {
853             if(currentPopup.isDirectory())
854             {
855                 Log.debug("This is a directory, not a file.");
856
857                 return;
858             }
859
860             String JavaDoc url = JFtp.localDir.getPath() + currentPopup.toString();
861             showContentWindow(url, currentPopup);
862         }
863         else if(e.getSource() == runFile)
864         {
865             if(currentPopup.isDirectory())
866             {
867                 Log.debug("This is a directory, not a file.");
868
869                 return;
870             }
871
872             String JavaDoc url = JFtp.localDir.getPath() + currentPopup.toString();
873             showContentWindow("popup-run@"+url, currentPopup);
874         }
875         else if(e.getSource() == sorter)
876         {
877             sortMode = (String JavaDoc) sorter.getSelectedItem();
878
879             if(sortMode.equals("Date"))
880             {
881                 Settings.showLocalDateNoSize = true;
882             }
883             else
884             {
885                 Settings.showLocalDateNoSize = false;
886             }
887
888             fresh();
889         }
890         else if(e.getActionCommand().equals("cdUp"))
891         {
892             chdir("..");
893         }
894     }
895
896     private void copy(Object JavaDoc[] fRaw, String JavaDoc path, String JavaDoc offset, String JavaDoc target)
897                throws Exception JavaDoc
898     {
899         String JavaDoc[] files = new String JavaDoc[fRaw.length];
900
901         for(int j = 0; j < fRaw.length; j++)
902         {
903             files[j] = fRaw[j].toString();
904         }
905
906         for(int i = 0; i < files.length; i++)
907         {
908             File JavaDoc f = new File JavaDoc(path + offset + files[i]);
909             BufferedInputStream JavaDoc in = null;
910             BufferedOutputStream JavaDoc out = null;
911             byte[] buf = new byte[4096];
912
913             if(f.exists() && !f.isDirectory())
914             {
915                 in = new BufferedInputStream JavaDoc(new FileInputStream JavaDoc(path + offset +
916                                                                  files[i]));
917                 out = new BufferedOutputStream JavaDoc(new FileOutputStream JavaDoc(target +
918                                                                     offset +
919                                                                     files[i]));
920
921                 int len = 0;
922
923                 while(in != null)
924                 {
925                     len = in.read(buf);
926
927                     if(len == StreamTokenizer.TT_EOF)
928                     {
929                         break;
930                     }
931
932                     out.write(buf, 0, len);
933                 }
934
935                 out.flush();
936                 out.close();
937             }
938             else if(f.exists())
939             {
940                 if(!files[i].endsWith("/"))
941                 {
942                     files[i] = files[i] + "/";
943                 }
944
945                 File JavaDoc f2 = new File JavaDoc(target + offset + files[i]);
946
947                 if(!f.exists())
948                 {
949                     f.mkdir();
950                 }
951
952                 copy(f.list(), path, offset + files[i], target);
953             }
954         }
955     }
956
957     /**
958     * Initiate a tranfer with ui locking enabled
959     */

960     public synchronized void blockedTransfer(int index)
961     {
962         tmpindex = index;
963
964         Runnable JavaDoc r = new Runnable JavaDoc()
965         {
966             public void run()
967             { // --------------- local -------------------
968

969                 boolean block = !Settings.getEnableMultiThreading();
970
971                 if(!(con instanceof FtpConnection))
972                 {
973                     block = true;
974                 }
975
976                 if(block || Settings.getNoUploadMultiThreading())
977                 {
978                     lock(false);
979                 }
980
981                 transfer(tmpindex);
982
983                 if(block || Settings.getNoUploadMultiThreading())
984                 {
985                     unlock(false);
986                 }
987
988                 //{
989
//JFtp.remoteDir.fresh();
990
//unlock(false);
991
//}
992
}
993         };
994
995         Thread JavaDoc t = new Thread JavaDoc(r);
996         t.start();
997     }
998
999     /**
1000    * Lock the gui.
1001    */

1002    public void lock(boolean first)
1003    {
1004        JFtp.uiBlocked = true;
1005        jl.setEnabled(false);
1006
1007        if(!first)
1008        {
1009            JFtp.remoteDir.lock(true);
1010        }
1011    }
1012
1013    /**
1014    * Unlock the gui.
1015    */

1016    public void unlock(boolean first)
1017    {
1018        JFtp.uiBlocked = false;
1019        jl.setEnabled(true);
1020
1021        if(!first)
1022        {
1023            JFtp.remoteDir.unlock(true);
1024        }
1025    }
1026
1027    /**
1028    * Do a hard UI refresh - do no longer call this directly, use
1029    * safeUpdate() instead.
1030    */

1031    public void fresh()
1032    {
1033        if(JFtp.mainFrame != null)
1034        {
1035            JFtp.mainFrame.setCursor(Cursor.WAIT_CURSOR);
1036        }
1037
1038        String JavaDoc i = "";
1039        int idx = jl.getSelectedIndex();
1040
1041        if(idx >= 0)
1042        {
1043            Object JavaDoc o = jl.getSelectedValue();
1044
1045            if(o != null)
1046            {
1047                i = o.toString();
1048            }
1049        }
1050
1051        chdir(path);
1052
1053        if((idx >= 0) && (idx < jl.getModel().getSize()))
1054        {
1055            if(jl.getModel().getElementAt(idx).toString().equals(i))
1056            {
1057                jl.setSelectedIndex(idx);
1058            }
1059            else
1060            {
1061                jl.setSelectedIndex(0);
1062            }
1063        }
1064
1065        update();
1066        
1067        if(JFtp.mainFrame != null)
1068        {
1069            JFtp.mainFrame.setCursor(Cursor.DEFAULT_CURSOR);
1070        }
1071    }
1072
1073    /**
1074    * Transfers all selected files
1075    */

1076    public synchronized void transfer()
1077    {
1078        boolean[] bFileSelected = new boolean[dirEntry.length + 1];
1079        DirEntry[] cacheEntry = new DirEntry[dirEntry.length];
1080        System.arraycopy(dirEntry, 0, cacheEntry, 0, cacheEntry.length);
1081
1082        for(int i = 0; i < dirEntry.length; i++)
1083        {
1084            bFileSelected[i] = cacheEntry[i].selected;
1085
1086            if(!cacheEntry[i].equals(dirEntry[i]))
1087            {
1088                Log.out("mismatch");
1089            }
1090        }
1091
1092        for(int i = 0; i < cacheEntry.length; i++)
1093        {
1094            if(bFileSelected[i])
1095            {
1096                startTransfer(cacheEntry[i]);
1097            }
1098        }
1099    }
1100
1101    /**
1102    * Start a file transfer.
1103    * Depending on the local and remote connection types some things like
1104    * local working directory have to be set, resuming may have to be checked etc.
1105    * As with ftp to ftp transfers the action used to download a file might actually be
1106    * an upload.
1107    *
1108    * WARNING: If you do anything here, please check RemoteDir.startTransfer(), too!
1109    */

1110    public void startTransfer(DirEntry entry)
1111    {
1112        if(con instanceof FilesystemConnection &&
1113               JFtp.remoteDir.getCon() instanceof FtpConnection)
1114        {
1115            if((entry.getRawSize() < Settings.smallSizeUp) &&
1116                   !entry.isDirectory())
1117            {
1118                JFtp.remoteDir.getCon().upload(path + entry.file);
1119            }
1120            else
1121            {
1122                JFtp.remoteDir.getCon().handleUpload(path + entry.file);
1123            }
1124        }
1125        else if(con instanceof FtpConnection &&
1126                    JFtp.remoteDir.getCon() instanceof FtpConnection)
1127        {
1128            // local: ftp, remote: ftp
1129
if(entry.isDirectory())
1130            {
1131                Log.debug("Directory transfer between remote connections is not supported yet!");
1132
1133                return;
1134            }
1135
1136            Log.out("direct ftp transfer started (upload)");
1137            ((FtpConnection) JFtp.remoteDir.getCon()).upload(entry.file,
1138                                                             ((FtpConnection) JFtp.localDir.getCon()).getDownloadInputStream(path +
1139                                                                                                                             entry.file));
1140        }
1141        else if(con instanceof FtpConnection &&
1142                    JFtp.remoteDir.getCon() instanceof FilesystemConnection)
1143        {
1144            con.setLocalPath(JFtp.remoteDir.getPath());
1145            con.handleDownload(path + entry.file);
1146        }
1147        else if(con instanceof FilesystemConnection &&
1148                    JFtp.remoteDir.getCon() instanceof FilesystemConnection)
1149        {
1150            con.upload(entry.file);
1151            JFtp.remoteDir.actionPerformed(con, "FRESH");
1152        }
1153        else if(con instanceof FilesystemConnection)
1154        {
1155            // local: file, remote: smb,sftp,nfs
1156
JFtp.remoteDir.getCon().handleUpload(entry.file);
1157            JFtp.remoteDir.actionPerformed(con, "FRESH");
1158        }
1159        else
1160        {
1161            if(entry.isDirectory())
1162            {
1163                Log.debug("Directory transfer between remote connections is not supported yet!");
1164
1165                return;
1166            }
1167
1168            Log.out("direct transfer started (upload)");
1169            JFtp.remoteDir.getCon().upload(entry.file,
1170                                           JFtp.localDir.getCon()
1171                                                        .getDownloadInputStream(path +
1172                                                                                entry.file));
1173            JFtp.remoteDir.actionPerformed(con, "FRESH");
1174        }
1175    }
1176
1177    /**
1178    * Transfers single file, or all selected files if index is -1
1179    */

1180    public void transfer(int i)
1181    {
1182        if(i == -2)
1183        {
1184            transfer();
1185
1186            return;
1187        }
1188        else if(dirEntry[i].selected)
1189        {
1190            startTransfer(dirEntry[i]);
1191        }
1192    }
1193
1194    /**
1195    * Safely refresh the UI.
1196    */

1197    public void safeUpdate()
1198    {
1199        UpdateDaemon.updateLocalDir();
1200    }
1201
1202    /**
1203    * Called by FtpConnection
1204    */

1205    public void actionPerformed(Object JavaDoc target, String JavaDoc msg)
1206    {
1207        //System.out.print(msg);
1208
//fresh();
1209
safeUpdate();
1210    }
1211
1212    /**
1213    * Called by FtpConnection, DownloadList is updated from here
1214    */

1215    public void updateProgress(String JavaDoc file, String JavaDoc type, long bytes) // only for url-downloads, for other see RemoteDir
1216
{
1217        if((dList == null) || (dirEntry == null))
1218        {
1219            return;
1220        }
1221
1222        boolean flag = false;
1223
1224        if(file.endsWith("/") && (file.length() > 1))
1225        {
1226            flag = true;
1227            file = file.substring(0, file.lastIndexOf("/"));
1228        }
1229
1230        file = file.substring(file.lastIndexOf("/") + 1);
1231
1232        if(flag)
1233        {
1234            file = file + "/";
1235        }
1236
1237        long s = 0;
1238
1239        if(JFtp.dList.sizeCache.containsKey(file))
1240        {
1241            s = ((Long JavaDoc) JFtp.dList.sizeCache.get(file)).longValue();
1242        }
1243        else
1244        {
1245            s = new File JavaDoc(getPath() + file).length();
1246            JFtp.dList.sizeCache.put(file, new Long JavaDoc(s));
1247        }
1248
1249        dList.updateList(file, type, bytes, s);
1250    }
1251
1252    /**
1253    * Called by FtpConnection
1254    */

1255    public void connectionInitialized(BasicConnection con)
1256    {
1257    }
1258
1259    /**
1260    * Called by FtpConnection
1261    */

1262    public void actionFinished(BasicConnection con)
1263    {
1264        //fresh();
1265
safeUpdate();
1266    }
1267
1268    /**
1269    * Called by FtpConnection
1270    */

1271    public void connectionFailed(BasicConnection con, String JavaDoc reason)
1272    {
1273    }
1274
1275    private void setDate()
1276    {
1277        if(!(con instanceof FtpConnection) &&
1278               !(con instanceof FilesystemConnection))
1279        {
1280            try
1281            {
1282                sorter.removeItem("Date");
1283            }
1284            catch(Exception JavaDoc ex)
1285            {
1286            }
1287
1288            dateEnabled = false;
1289
1290            return;
1291        }
1292
1293        //Log.debug(">>> date gui init (local)");
1294
if((con instanceof FtpConnection) &&
1295               (((FtpConnection) con).dateVector.size() > 0))
1296        {
1297            if(!dateEnabled)
1298            {
1299                sorter.addItem("Date");
1300                dateEnabled = true;
1301                UpdateDaemon.updateRemoteDirGUI();
1302            }
1303        }
1304        else if((con instanceof FilesystemConnection) &&
1305                    (((FilesystemConnection) con).dateVector.size() > 0))
1306        {
1307            if(!dateEnabled)
1308            {
1309                sorter.addItem("Date");
1310                dateEnabled = true;
1311                UpdateDaemon.updateRemoteDirGUI();
1312            }
1313        }
1314        else
1315        {
1316            if(dateEnabled)
1317            {
1318                sorter.removeItem("Date");
1319                dateEnabled = false;
1320                Settings.showLocalDateNoSize = false;
1321                UpdateDaemon.updateRemoteDirGUI();
1322            }
1323        }
1324    }
1325
1326    /**
1327    * Called by FtpConnection
1328    */

1329    public void updateRemoteDirectory(BasicConnection c)
1330    {
1331        if(con instanceof FtpConnection)
1332        {
1333            path = ((FtpConnection) con).getCachedPWD();
1334        }
1335        else if(con instanceof SmbConnection && !path.startsWith("smb://"))
1336        {
1337            path = con.getPWD();
1338        }
1339        else
1340        {
1341            path = con.getPWD();
1342        }
1343
1344        //Log.out(">>> update local dir");
1345
//fresh();
1346
safeUpdate();
1347    }
1348
1349    /**
1350    * Extract a zip file and change to the directory
1351    */

1352    private void setZipFilePath(DirEntry entry)
1353    {
1354        if(JFtp.mainFrame != null)
1355        {
1356            JFtp.mainFrame.setCursor(Cursor.WAIT_CURSOR);
1357        }
1358
1359        String JavaDoc n = entry.toString();
1360        String JavaDoc tmp = path + n + "-dir/";
1361        Log.debug("\nExtracting: " + path + n);
1362
1363        File JavaDoc tmpDir = new File JavaDoc(tmp);
1364
1365        if(tmpDir.exists() || tmpDir.mkdir())
1366        {
1367            try
1368            {
1369                ZipFile JavaDoc z = new ZipFile JavaDoc(path + n);
1370                Enumeration JavaDoc e = z.entries();
1371
1372                while(e.hasMoreElements())
1373                {
1374                    ZipEntry JavaDoc z1 = (ZipEntry JavaDoc) e.nextElement();
1375                    Log.debug("-> " + z1.getName());
1376
1377                    BufferedInputStream JavaDoc in = new BufferedInputStream JavaDoc(z.getInputStream(z1));
1378                    BufferedOutputStream JavaDoc out = new BufferedOutputStream JavaDoc(new FileOutputStream JavaDoc(tmp +
1379                                                                                             z1.getName()));
1380                    byte[] buf = new byte[8192];
1381
1382                    while(in.read(buf, 0, 8192) != StreamTokenizer.TT_EOF)
1383                    {
1384                        out.write(buf);
1385                    }
1386
1387                    out.flush();
1388                    out.close();
1389                    in.close();
1390                }
1391
1392                chdir(tmp);
1393            }
1394            catch(IOException JavaDoc ex)
1395            {
1396                ex.printStackTrace();
1397                Log.debug("ERROR: " + ex);
1398            }
1399        }
1400        else
1401        {
1402            Log.debug("Cannot create directory, skipping extraction...");
1403        }
1404
1405        //chdir(path + tgt);
1406
if(JFtp.mainFrame != null)
1407        {
1408            JFtp.mainFrame.setCursor(Cursor.DEFAULT_CURSOR);
1409        }
1410    }
1411
1412    /**
1413    * Mime type handler for doubleclicks on files
1414    */

1415    public void showContentWindow(String JavaDoc url, DirEntry d)
1416    {
1417        //------- popup -> run
1418
if(Settings.runtimeCommands > 0 && url.startsWith("popup-run@")) {
1419            String JavaDoc ext = url.substring(10);
1420            
1421            try {
1422                System.out.println("xx: "+ext);
1423                if(!Settings.askToRun || (Settings.askToRun && UITool.askToRun(this))) UIUtils.runCommand(ext);
1424            }
1425            catch(Exception JavaDoc ex) {
1426                Log.out("Could not launch file: "+ ext);
1427            }
1428            
1429            return;
1430        }
1431        
1432        //------------
1433

1434        if(d.toString().endsWith(".zip"))
1435        {
1436            setZipFilePath(d);
1437        }
1438        else
1439        {
1440            try
1441            {
1442                url = "file://" + url;
1443
1444                // -------- images ----------
1445
String JavaDoc ext = url.toLowerCase();
1446
1447                if(ext.endsWith(".jpg") || ext.endsWith(".gif") ||
1448                       ext.endsWith(".jpeg") || ext.endsWith(".png"))
1449                {
1450                    ImageViewer d1 = new ImageViewer(url);
1451                    JFtp.desktop.add(d1, new Integer JavaDoc(Integer.MAX_VALUE - 11));
1452
1453                    return;
1454                }
1455
1456                
1457                if(Settings.runtimeCommands > 1) {
1458                    try {
1459                        if(!Settings.askToRun || (Settings.askToRun && UITool.askToRun(this))) {
1460                            UIUtils.runCommand(ext);
1461                            return;
1462                        }
1463                    }
1464                    catch(Exception JavaDoc ex) {
1465                        Log.out("Could not launch file: "+ ext);
1466                    }
1467                }
1468                
1469                // -----------------
1470
if(d.getRawSize() > 200000)
1471                {
1472                    Log.debug("File is too big - 200kb is the maximum, sorry.");
1473
1474                    return;
1475                }
1476
1477                HPanel f = new HPanel();
1478
1479                JEditorPane JavaDoc pane = new JEditorPane JavaDoc(url);
1480                pane.setEditable(false);
1481
1482                if(!pane.getEditorKit().getContentType().equals("text/html") &&
1483                       !pane.getEditorKit().getContentType().equals("text/rtf"))
1484                {
1485                    if(!pane.getEditorKit().getContentType().equals("text/plain"))
1486                    {
1487                        Log.debug("Nothing to do with this filetype - use the buttons if you want to transfer files.");
1488
1489                        return;
1490                    }
1491
1492                    pane.setEditable(false);
1493                }
1494
1495                JScrollPane JavaDoc jsp = new JScrollPane JavaDoc(pane);
1496
1497                f.setLayout(new BorderLayout JavaDoc());
1498                f.add("Center", jsp);
1499                JFtp.statusP.jftp.addToDesktop(url, f, 600, 400);
1500            }
1501            catch(Exception JavaDoc ex)
1502            {
1503                Log.debug("File error: " + ex);
1504            }
1505        }
1506    }
1507
1508    public void keyPressed(KeyEvent JavaDoc e)
1509    {
1510        if(e.getKeyCode() == KeyEvent.VK_ENTER)
1511        {
1512            Object JavaDoc o = jl.getSelectedValue();
1513
1514            if(o == null)
1515            {
1516                return;
1517            }
1518
1519            String JavaDoc tmp = ((DirEntry) o).toString();
1520
1521            if(tmp.endsWith("/") || tmp.equals(".."))
1522            {
1523                chdir(tmp);
1524            }
1525            else
1526            {
1527                showContentWindow(path + tmp, (DirEntry) o);
1528            }
1529        }
1530        else if(e.getKeyCode() == KeyEvent.VK_SPACE)
1531        {
1532            int x = ((DirPanel) JFtp.remoteDir).jl.getSelectedIndex();
1533
1534            if(x == -1)
1535            {
1536                x = 0;
1537            }
1538
1539            ((DirPanel) JFtp.remoteDir).jl.grabFocus();
1540            ((DirPanel) JFtp.remoteDir).jl.setSelectedIndex(x);
1541        }
1542    }
1543
1544    public void keyReleased(KeyEvent JavaDoc e)
1545    {
1546    }
1547
1548    public void keyTyped(KeyEvent JavaDoc e)
1549    {
1550    }
1551}
1552
Popular Tags