/
MainController.java
1428 lines (1315 loc) · 58.3 KB
/
MainController.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package ch.cyberduck.ui.cocoa;
/*
* Copyright (c) 2005 David Kocher. All rights reserved.
* http://cyberduck.ch/
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* Bug fixes, suggestions and comments should be sent to:
* dkocher@cyberduck.ch
*/
import ch.cyberduck.core.*;
import ch.cyberduck.core.Collection;
import ch.cyberduck.core.aquaticprime.License;
import ch.cyberduck.core.aquaticprime.LicenseFactory;
import ch.cyberduck.core.i18n.Locale;
import ch.cyberduck.core.importer.*;
import ch.cyberduck.core.serializer.HostReaderFactory;
import ch.cyberduck.core.serializer.ProtocolReaderFactory;
import ch.cyberduck.core.sparkle.Updater;
import ch.cyberduck.core.threading.AbstractBackgroundAction;
import ch.cyberduck.core.threading.DefaultMainAction;
import ch.cyberduck.ui.cocoa.application.*;
import ch.cyberduck.ui.cocoa.delegate.*;
import ch.cyberduck.ui.cocoa.foundation.*;
import ch.cyberduck.ui.cocoa.urlhandler.URLSchemeHandlerConfiguration;
import ch.cyberduck.ui.growl.Growl;
import org.rococoa.Foundation;
import org.rococoa.ID;
import org.rococoa.Rococoa;
import org.rococoa.cocoa.foundation.NSInteger;
import org.rococoa.cocoa.foundation.NSRect;
import org.rococoa.cocoa.foundation.NSUInteger;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.text.MessageFormat;
import java.util.*;
import java.util.concurrent.CountDownLatch;
/**
* Setting the main menu and implements application delegate methods
*
* @version $Id$
*/
public class MainController extends BundleController implements NSApplication.Delegate {
private static Logger log = Logger.getLogger(MainController.class);
/**
* Apple event constants<br>
* **********************************************************************************************<br>
* <i>native declaration : /Developer/SDKs/MacOSX10.5.sdk/usr/include/AvailabilityMacros.h:117</i>
*/
public static final int kInternetEventClass = 1196773964;
/**
* Apple event constants<br>
* **********************************************************************************************<br>
* <i>native declaration : /Developer/SDKs/MacOSX10.5.sdk/usr/include/AvailabilityMacros.h:118</i>
*/
public static final int kAEGetURL = 1196773964;
/**
* Apple event constants<br>
* **********************************************************************************************<br>
* <i>native declaration : /Developer/SDKs/MacOSX10.5.sdk/usr/include/AvailabilityMacros.h:119</i>
*/
public static final int kAEFetchURL = 1179996748;
/// 0x2d2d2d2d
public static final int keyAEResult = 757935405;
public MainController() {
this.loadBundle();
}
@Override
public void awakeFromNib() {
NSAppleEventManager.sharedAppleEventManager().setEventHandler_andSelector_forEventClass_andEventID(
this.id(), Foundation.selector("handleGetURLEvent:withReplyEvent:"), kInternetEventClass, kAEGetURL);
super.awakeFromNib();
}
/**
* Extract the URL from the Apple event and handle it here.
*
* @param event
* @param reply
*/
public void handleGetURLEvent_withReplyEvent(NSAppleEventDescriptor event, NSAppleEventDescriptor reply) {
log.debug("Received URL from Apple Event:" + event);
final NSAppleEventDescriptor param = event.paramDescriptorForKeyword(keyAEResult);
if(null == param) {
log.error("No URL parameter");
return;
}
final String url = param.stringValue();
if(StringUtils.isEmpty(url)) {
log.error("URL parameter is empty");
return;
}
if("x-cyberduck-action:update".equals(url)) {
this.updateMenuClicked(null);
}
else {
final Host h = Host.parse(url);
if(StringUtils.isNotEmpty(h.getDefaultPath())) {
if(!h.getDefaultPath().endsWith(String.valueOf(Path.DELIMITER))) {
final Session s = SessionFactory.createSession(h);
final Path p = PathFactory.createPath(s, h.getDefaultPath(), Path.FILE_TYPE);
if(StringUtils.isNotBlank(p.getExtension())) {
TransferController.instance().startTransfer(new DownloadTransfer(p));
return;
}
}
}
for(BrowserController controller : MainController.getBrowsers()) {
if(controller.isMounted()) {
if(controller.getSession().getHost().toURL().equals(h.toURL())) {
// Handle browser window already connected to the same host. #4215
controller.window().makeKeyAndOrderFront(null);
return;
}
}
}
BrowserController doc = newDocument();
doc.mount(h);
}
}
private Updater updater;
/**
*
*/
@Action
public void updateMenuClicked(ID sender) {
if(null == updater) {
updater = Updater.create();
}
updater.checkForUpdates(null);
}
@Outlet
private NSMenu applicationMenu;
public void setApplicationMenu(NSMenu menu) {
this.applicationMenu = menu;
this.updateLicenseMenu();
this.updateUpdateMenu();
}
/**
* Set name of key in menu item
*/
private void updateLicenseMenu() {
License key = LicenseFactory.find();
if(key.isReceipt()) {
this.applicationMenu.removeItemAtIndex(new NSInteger(5));
this.applicationMenu.removeItemAtIndex(new NSInteger(4));
}
else {
NSDictionary KEY_FONT_ATTRIBUTES = NSDictionary.dictionaryWithObjectsForKeys(
NSArray.arrayWithObjects(NSFont.userFontOfSize(NSFont.smallSystemFontSize()), NSColor.darkGrayColor()),
NSArray.arrayWithObjects(NSAttributedString.FontAttributeName, NSAttributedString.ForegroundColorAttributeName)
);
this.applicationMenu.itemAtIndex(new NSInteger(5)).setAttributedTitle(
NSAttributedString.attributedStringWithAttributes(key.toString(), KEY_FONT_ATTRIBUTES)
);
}
}
/**
* Remove software update menu item if no update feed available
*/
private void updateUpdateMenu() {
if(null == Updater.getFeed()) {
this.applicationMenu.removeItemAtIndex(new NSInteger(1));
}
}
@Outlet
private NSMenu encodingMenu;
public void setEncodingMenu(NSMenu encodingMenu) {
this.encodingMenu = encodingMenu;
for(String charset : availableCharsets()) {
this.encodingMenu.addItemWithTitle_action_keyEquivalent(charset, Foundation.selector("encodingMenuClicked:"), "");
}
}
@Outlet
private NSMenu columnMenu;
public void setColumnMenu(NSMenu columnMenu) {
this.columnMenu = columnMenu;
Map<String, String> columns = new HashMap<String, String>();
columns.put("browser.columnKind", Locale.localizedString("Kind"));
columns.put("browser.columnExtension", Locale.localizedString("Extension"));
columns.put("browser.columnSize", Locale.localizedString("Size"));
columns.put("browser.columnModification", Locale.localizedString("Modified"));
columns.put("browser.columnOwner", Locale.localizedString("Owner"));
columns.put("browser.columnGroup", Locale.localizedString("Group"));
columns.put("browser.columnPermissions", Locale.localizedString("Permissions"));
Iterator<String> identifiers = columns.keySet().iterator();
int i = 0;
for(Iterator iter = columns.values().iterator(); iter.hasNext(); i++) {
NSMenuItem item = this.columnMenu.addItemWithTitle_action_keyEquivalent((String) iter.next(),
Foundation.selector("columnMenuClicked:"), "");
final String identifier = identifiers.next();
item.setState(Preferences.instance().getBoolean(identifier) ? NSCell.NSOnState : NSCell.NSOffState);
item.setRepresentedObject(identifier);
}
}
@Action
public void columnMenuClicked(final NSMenuItem sender) {
final String identifier = sender.representedObject();
final boolean enabled = !Preferences.instance().getBoolean(identifier);
sender.setState(enabled ? NSCell.NSOnState : NSCell.NSOffState);
Preferences.instance().setProperty(identifier, enabled);
BrowserController.updateBrowserTableColumns();
}
@Outlet
private NSMenu editMenu;
private EditMenuDelegate editMenuDelegate;
public void setEditMenu(NSMenu editMenu) {
this.editMenu = editMenu;
this.editMenuDelegate = new EditMenuDelegate() {
@Override
protected Local getSelectedFile() {
final List<BrowserController> browsers = MainController.getBrowsers();
for(BrowserController controller : browsers) {
if(controller.window().isKeyWindow()) {
return controller.getSelectedFile();
}
}
return null;
}
@Override
protected ID getTarget() {
return MainController.getBrowser().id();
}
};
this.editMenu.setDelegate(editMenuDelegate.id());
}
@Outlet
private NSMenu urlMenu;
private URLMenuDelegate urlMenuDelegate;
public void setUrlMenu(NSMenu urlMenu) {
this.urlMenu = urlMenu;
this.urlMenuDelegate = new CopyURLMenuDelegate() {
@Override
protected List<Path> getSelected() {
final List<BrowserController> browsers = MainController.getBrowsers();
for(BrowserController controller : browsers) {
if(controller.window().isKeyWindow()) {
List<Path> selected = controller.getSelectedPaths();
if(selected.isEmpty()) {
if(controller.isMounted()) {
return Collections.singletonList(controller.workdir());
}
}
return selected;
}
}
return Collections.emptyList();
}
};
this.urlMenu.setDelegate(urlMenuDelegate.id());
}
@Outlet
private NSMenu openUrlMenu;
private URLMenuDelegate openUrlMenuDelegate;
public void setOpenUrlMenu(NSMenu openUrlMenu) {
this.openUrlMenu = openUrlMenu;
this.openUrlMenuDelegate = new OpenURLMenuDelegate() {
@Override
protected List<Path> getSelected() {
final List<BrowserController> browsers = MainController.getBrowsers();
for(BrowserController controller : browsers) {
if(controller.window().isKeyWindow()) {
List<Path> selected = controller.getSelectedPaths();
if(selected.isEmpty()) {
if(controller.isMounted()) {
return Collections.singletonList(controller.workdir());
}
}
return selected;
}
}
return Collections.emptyList();
}
};
this.openUrlMenu.setDelegate(openUrlMenuDelegate.id());
}
@Outlet
private NSMenu archiveMenu;
private ArchiveMenuDelegate archiveMenuDelegate;
public void setArchiveMenu(NSMenu archiveMenu) {
this.archiveMenu = archiveMenu;
this.archiveMenuDelegate = new ArchiveMenuDelegate() {
@Override
protected ID getTarget() {
return MainController.getBrowser().id();
}
};
this.archiveMenu.setDelegate(archiveMenuDelegate.id());
}
@Outlet
private NSMenu bookmarkMenu;
private BookmarkMenuDelegate bookmarkMenuDelegate;
public void setBookmarkMenu(NSMenu bookmarkMenu) {
this.bookmarkMenu = bookmarkMenu;
this.bookmarkMenuDelegate = new BookmarkMenuDelegate() {
@Override
protected ID getTarget() {
return MainController.getBrowser().id();
}
};
this.bookmarkMenu.setDelegate(bookmarkMenuDelegate.id());
}
@Outlet
private NSMenu historyMenu;
private HistoryMenuDelegate historyMenuDelegate;
public void setHistoryMenu(NSMenu historyMenu) {
this.historyMenu = historyMenu;
this.historyMenuDelegate = new HistoryMenuDelegate() {
@Override
protected ID getTarget() {
return MainController.getBrowser().id();
}
};
this.historyMenu.setDelegate(historyMenuDelegate.id());
}
@Outlet
private NSMenu rendezvousMenu;
private RendezvousMenuDelegate rendezvousMenuDelegate;
public void setRendezvousMenu(NSMenu rendezvousMenu) {
this.rendezvousMenu = rendezvousMenu;
this.rendezvousMenuDelegate = new RendezvousMenuDelegate() {
@Override
protected ID getTarget() {
return MainController.getBrowser().id();
}
};
this.rendezvousMenu.setDelegate(rendezvousMenuDelegate.id());
}
@Action
public void historyMenuClicked(NSMenuItem sender) {
HistoryCollection.defaultCollection().open();
}
@Action
public void bugreportMenuClicked(final ID sender) {
openUrl(Preferences.instance().getProperty("website.bug"));
}
@Action
public void helpMenuClicked(final ID sender) {
openUrl(Preferences.instance().getProperty("website.help"));
}
@Action
public void faqMenuClicked(final ID sender) {
LocalFactory.createLocal(NSBundle.mainBundle().pathForResource_ofType("Cyberduck FAQ", "rtfd")).open();
}
@Action
public void licenseMenuClicked(final ID sender) {
LocalFactory.createLocal(NSBundle.mainBundle().pathForResource_ofType("License", "txt")).open();
}
@Action
public void acknowledgmentsMenuClicked(final ID sender) {
LocalFactory.createLocal(NSBundle.mainBundle().pathForResource_ofType("Acknowledgments", "rtf")).open();
}
@Action
public void websiteMenuClicked(final ID sender) {
openUrl(Preferences.instance().getProperty("website.home"));
}
@Action
public void forumMenuClicked(final ID sender) {
openUrl(Preferences.instance().getProperty("website.forum"));
}
@Action
public void donateMenuClicked(final ID sender) {
openUrl(Preferences.instance().getProperty("website.donate"));
}
@Action
public void aboutMenuClicked(final ID sender) {
NSDictionary dict = NSDictionary.dictionaryWithObjectsForKeys(
NSArray.arrayWithObjects(
NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString").toString(),
NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleVersion").toString()),
NSArray.arrayWithObjects(
"ApplicationVersion",
"Version")
);
NSApplication.sharedApplication().orderFrontStandardAboutPanelWithOptions(dict);
}
@Action
public void feedbackMenuClicked(final ID sender) {
openUrl(Preferences.instance().getProperty("mail.feedback")
+ "?subject=" + Preferences.instance().getProperty("application.name") + "-" + Preferences.instance().getProperty("application.version"));
}
@Action
public void preferencesMenuClicked(final ID sender) {
PreferencesController controller = PreferencesController.instance();
controller.window().makeKeyAndOrderFront(null);
}
@Action
public void newDownloadMenuClicked(final ID sender) {
this.showTransferQueueClicked(sender);
SheetController c = new DownloadController(TransferController.instance());
c.beginSheet();
}
@Action
public void newBrowserMenuClicked(final ID sender) {
this.openDefaultBookmark(MainController.newDocument(true));
}
@Action
public void showTransferQueueClicked(final ID sender) {
TransferController c = TransferController.instance();
c.window().makeKeyAndOrderFront(null);
}
@Action
public void showActivityWindowClicked(final ID sender) {
ActivityController c = ActivityController.instance();
if(c.isVisible()) {
c.window().close();
}
else {
c.window().orderFront(null);
}
}
/**
* @param app
* @param filename
* @return
*/
public boolean application_openFile(NSApplication app, String filename) {
log.debug("applicationOpenFile:" + filename);
final Local f = LocalFactory.createLocal(filename);
if(f.exists()) {
if("duck".equals(f.getExtension())) {
final Host host = HostReaderFactory.instance().read(f);
MainController.newDocument().mount(host);
return true;
}
else if("cyberducklicense".equals(f.getExtension())) {
final License l = LicenseFactory.create(f);
if(l.verify()) {
final NSAlert alert = NSAlert.alert(
l.toString(),
Locale.localizedString("Thanks for your support! Your contribution helps to further advance development to make Cyberduck even better.", "License")
+ "\n\n"
+ Locale.localizedString("Your donation key has been copied to the Application Support folder.", "License"),
Locale.localizedString("Continue", "License"), //default
null, //other
null);
alert.setAlertStyle(NSAlert.NSInformationalAlertStyle);
if(this.alert(alert) == SheetCallback.DEFAULT_OPTION) {
f.copy(LocalFactory.createLocal(Preferences.instance().getProperty("application.support.path"), f.getName()));
for(BrowserController c : MainController.getBrowsers()) {
c.removeDonateWindowTitle();
}
this.updateLicenseMenu();
}
}
else {
final NSAlert alert = NSAlert.alert(
Locale.localizedString("Not a valid donation key", "License"),
Locale.localizedString("This donation key does not appear to be valid.", "License"),
Locale.localizedString("Continue", "License"), //default
null, //other
null);
alert.setAlertStyle(NSAlert.NSWarningAlertStyle);
alert.setShowsHelp(true);
alert.setDelegate(new ProxyController() {
public boolean alertShowHelp(NSAlert alert) {
StringBuilder site = new StringBuilder(Preferences.instance().getProperty("website.help"));
site.append("/").append("faq");
openUrl(site.toString());
return true;
}
}.id());
this.alert(alert);
}
return true;
}
else if("cyberduckprofile".equals(f.getExtension())) {
final Protocol profile = ProtocolReaderFactory.instance().read(f);
profile.register();
final Host host = new Host(profile, profile.getDefaultHostname(), profile.getDefaultPort());
MainController.newDocument().addBookmark(host);
// Register in application support
final Local profiles = LocalFactory.createLocal(Preferences.instance().getProperty("application.support.path"), "Profiles");
profiles.mkdir(true);
f.copy(LocalFactory.createLocal(profiles, f.getName()));
}
else {
// Upload file
this.background(new AbstractBackgroundAction() {
public void run() {
// Wait until bookmarks are loaded
try {
loader.await();
}
catch(InterruptedException e) {
log.error(e.getMessage());
}
}
@Override
public void cleanup() {
upload(f);
}
@Override
public String getActivity() {
return "Open File";
}
});
return true;
}
}
return false;
}
/**
* @param f
* @return
*/
private boolean upload(Local f) {
return this.upload(Collections.singletonList(f));
}
/**
* @param files
* @return
*/
private boolean upload(final List<Local> files) {
// Selected bookmark
Host open = null;
String workdir = String.valueOf(Path.DELIMITER);
for(BrowserController controller : MainController.getBrowsers()) {
if(controller.isMounted()) {
open = controller.getSession().getHost();
workdir = controller.workdir().getAbsolute();
if(1 == MainController.getBrowsers().size()) {
// If only one browser window upload to current working directory with no bookmark selection
this.upload(open, files, workdir);
return true;
}
break;
}
}
if(BookmarkCollection.defaultCollection().isEmpty()) {
log.warn("No bookmark for upload");
return false;
}
final NSPopUpButton bookmarksPopup = NSPopUpButton.buttonWithFrame(new NSRect(0, 26));
bookmarksPopup.setToolTip(Locale.localizedString("Bookmarks"));
for(Host b : BookmarkCollection.defaultCollection()) {
String title = b.getNickname();
int i = 1;
while(bookmarksPopup.itemWithTitle(title) != null) {
title = b.getNickname() + "-" + i;
i++;
}
bookmarksPopup.addItemWithTitle(title);
bookmarksPopup.lastItem().setImage(IconCache.iconNamed(b.getProtocol().icon(), 16));
bookmarksPopup.lastItem().setRepresentedObject(b.getUuid());
if(b.equals(open)) {
bookmarksPopup.selectItemAtIndex(bookmarksPopup.indexOfItem(bookmarksPopup.lastItem()));
}
}
if(null == open) {
int i = 0;
for(Host bookmark : BookmarkCollection.defaultCollection()) {
boolean found = false;
// Pick the bookmark with the same download location
for(Local file : files) {
if(file.isChild(bookmark.getDownloadFolder())) {
bookmarksPopup.selectItemAtIndex(new NSInteger(i));
found = true;
break;
}
}
if(found) {
break;
}
i++;
}
}
if(-1 == bookmarksPopup.indexOfSelectedItem().intValue()) {
// No bookmark for current browser found
bookmarksPopup.selectItemAtIndex(new NSInteger(0));
}
final TransferController t = TransferController.instance();
final Host mount = open;
final String destination = workdir;
AlertController alert = new AlertController(t, NSAlert.alert("Select Bookmark",
MessageFormat.format("Upload {0} to the selected bookmark.",
files.size() == 1 ? files.iterator().next().getName()
: MessageFormat.format(Locale.localizedString("{0} Files"), String.valueOf(files.size()))),
Locale.localizedString("Upload"),
Locale.localizedString("Cancel"),
null)) {
public void callback(int returncode) {
if(DEFAULT_OPTION == returncode) {
final String selected = bookmarksPopup.selectedItem().representedObject();
for(Host bookmark : BookmarkCollection.defaultCollection()) {
// Determine selected bookmark
if(bookmark.getUuid().equals(selected)) {
String parent = destination;
if(bookmark.equals(mount)) {
; // Use current working directory of browser for destination
}
else {
// No mounted browser
if(StringUtils.isNotBlank(bookmark.getDefaultPath())) {
parent = bookmark.getDefaultPath();
}
}
upload(bookmark, files, parent);
break;
}
}
}
}
@Override
protected boolean validateInput() {
return StringUtils.isNotEmpty(bookmarksPopup.selectedItem().representedObject());
}
};
alert.setAccessoryView(bookmarksPopup);
alert.beginSheet();
return true;
}
/**
* @param bookmark
* @param files
* @param destination
*/
private void upload(Host bookmark, List<Local> files, String destination) {
final Session session = SessionFactory.createSession(bookmark);
List<Path> roots = new ArrayList<Path>();
for(Local file : files) {
roots.add(PathFactory.createPath(session, destination, file));
}
final TransferController t = TransferController.instance();
t.startTransfer(new UploadTransfer(roots));
}
/**
* Sent directly by theApplication to the delegate. The method should attempt to open the file filename,
* returning true if the file is successfully opened, and false otherwise. By design, a
* file opened through this method is assumed to be temporary its the application's
* responsibility to remove the file at the appropriate time.
*
* @param app
* @param filename
* @return
*/
public boolean application_openTempFile(NSApplication app, String filename) {
log.debug("applicationOpenTempFile:" + filename);
return this.application_openFile(app, filename);
}
/**
* Invoked immediately before opening an untitled file. Return false to prevent
* the application from opening an untitled file; return true otherwise.
* Note that applicationOpenUntitledFile is invoked if this method returns true.
*
* @param sender
* @return
*/
public boolean applicationShouldOpenUntitledFile(NSApplication sender) {
log.debug("applicationShouldOpenUntitledFile");
return Preferences.instance().getBoolean("browser.openUntitled");
}
/**
* @return true if the file was successfully opened, false otherwise.
*/
public boolean applicationOpenUntitledFile(NSApplication app) {
log.debug("applicationOpenUntitledFile");
return false;
}
/**
* Mounts the default bookmark if any
*
* @param controller
*/
private void openDefaultBookmark(BrowserController controller) {
String defaultBookmark = Preferences.instance().getProperty("browser.defaultBookmark");
if(null == defaultBookmark) {
log.info("No default bookmark configured");
return; //No default bookmark given
}
Host bookmark = BookmarkCollection.defaultCollection().lookup(defaultBookmark);
if(null == bookmark) {
log.info("Default bookmark no more available");
return;
}
for(BrowserController browser : getBrowsers()) {
if(browser.hasSession()) {
if(browser.getSession().getHost().equals(bookmark)) {
log.debug("Default bookmark already mounted");
return;
}
}
}
log.debug("Mounting default bookmark " + bookmark);
controller.mount(bookmark);
}
/**
* These events are sent whenever the Finder reactivates an already running application
* because someone double-clicked it again or used the dock to activate it. By default
* the Application Kit will handle this event by checking whether there are any visible
* NSWindows (not NSPanels), and, if there are none, it goes through the standard untitled
* document creation (the same as it does if theApplication is launched without any document
* to open). For most document-based applications, an untitled document will be created.
* The application delegate will also get a chance to respond to the normal untitled document
* delegations. If you implement this method in your application delegate, it will be called
* before any of the default behavior happens. If you return true, then NSApplication will
* go on to do its normal thing. If you return false, then NSApplication will do nothing.
* So, you can either implement this method, do nothing, and return false if you do not
* want anything to happen at all (not recommended), or you can implement this method,
* handle the event yourself in some custom way, and return false.
*
* @param app
* @param visibleWindowsFound
* @return
*/
public boolean applicationShouldHandleReopen_hasVisibleWindows(NSApplication app, boolean visibleWindowsFound) {
log.debug("applicationShouldHandleReopen");
// While an application is open, the Dock icon has a symbol below it.
// When a user clicks an open application’s icon in the Dock, the application
// becomes active and all open unminimized windows are brought to the front;
// minimized document windows remain in the Dock. If there are no unminimized
// windows when the user clicks the Dock icon, the last minimized window should
// be expanded and made active. If no documents are open, the application should
// open a new window. (If your application is not document-based, display the
// application’s main window.)
if(MainController.getBrowsers().isEmpty() && !TransferController.instance().isVisible()) {
this.openDefaultBookmark(MainController.newDocument());
}
NSWindow miniaturized = null;
for(BrowserController controller : MainController.getBrowsers()) {
if(!controller.window().isMiniaturized()) {
return false;
}
if(null == miniaturized) {
miniaturized = controller.window();
}
}
if(null == miniaturized) {
return false;
}
miniaturized.deminiaturize(null);
return false;
}
// User bookmarks and thirdparty applications
private final CountDownLatch loader = new CountDownLatch(2);
/**
* Sent by the default notification center after the application has been launched and initialized but
* before it has received its first event. aNotification is always an
* ApplicationDidFinishLaunchingNotification. You can retrieve the NSApplication
* object in question by sending object to aNotification. The delegate can implement
* this method to perform further initialization. If the user started up the application
* by double-clicking a file, the delegate receives the applicationOpenFile message before receiving
* applicationDidFinishLaunching. (applicationWillFinishLaunching is sent before applicationOpenFile.)
*
* @param notification
*/
public void applicationDidFinishLaunching(NSNotification notification) {
if(log.isInfoEnabled()) {
log.info("Running Java " + System.getProperty("java.version") + " on " + System.getProperty("os.arch"));
log.info("Available localizations:" + NSBundle.mainBundle().localizations());
log.info("Current locale:" + java.util.Locale.getDefault());
}
if(Preferences.instance().getBoolean("browser.openUntitled")) {
MainController.newDocument();
}
if(Preferences.instance().getBoolean("queue.openByDefault")) {
this.showTransferQueueClicked(null);
}
if(Preferences.instance().getBoolean("browser.serialize")) {
this.background(new AbstractBackgroundAction() {
public void run() {
sessions.load();
}
@Override
public void cleanup() {
for(Host host : sessions) {
MainController.newDocument().mount(host);
}
sessions.clear();
}
});
}
this.background(new AbstractBackgroundAction() {
public void run() {
final BookmarkCollection c = BookmarkCollection.defaultCollection();
c.load();
loader.countDown();
}
@Override
public void cleanup() {
if(Preferences.instance().getBoolean("browser.openUntitled")) {
if(MainController.getBrowsers().isEmpty()) {
openDefaultBookmark(MainController.newDocument());
}
}
// Set delegate for NSService
NSApplication.sharedApplication().setServicesProvider(MainController.this.id());
}
@Override
public String getActivity() {
return "Loading Bookmarks";
}
});
this.background(new AbstractBackgroundAction() {
public void run() {
HistoryCollection.defaultCollection().load();
}
@Override
public String getActivity() {
return "Loading History";
}
});
this.background(new AbstractBackgroundAction() {
public void run() {
TransferCollection.defaultCollection().load();
}
@Override
public String getActivity() {
return "Loading Transfers";
}
});
this.background(new AbstractBackgroundAction() {
public void run() {
// Make sure we register to Growl first
Growl.instance().register();
}
@Override
public String getActivity() {
return "Registering Growl";
}
});
if(Preferences.instance().getBoolean("rendezvous.enable")) {
RendezvousFactory.instance().addListener(new RendezvousListener() {
public void serviceResolved(final String identifier, final Host host) {
if(Preferences.instance().getBoolean("rendezvous.loopback.supress")) {
try {
if(InetAddress.getByName(host.getHostname()).equals(InetAddress.getLocalHost())) {
log.info("Supressed Rendezvous notification for " + host);
return;
}
}
catch(UnknownHostException e) {
; //Ignore
}
}
invoke(new DefaultMainAction() {
public void run() {
Growl.instance().notifyWithImage("Bonjour", RendezvousFactory.instance().getDisplayedName(identifier), "rendezvous");
}
});
}
public void serviceLost(String servicename) {
;
}
});
}
if(Preferences.instance().getBoolean("defaulthandler.reminder")
&& Preferences.instance().getInteger("uses") > 0) {
if(!URLSchemeHandlerConfiguration.instance().isDefaultHandlerForURLScheme(
new String[]{Protocol.FTP.getScheme(), Protocol.FTP_TLS.getScheme(), Protocol.SFTP.getScheme()})) {
final NSAlert alert = NSAlert.alert(
Locale.localizedString("Set Cyberduck as default application for FTP and SFTP locations?", "Configuration"),
Locale.localizedString("As the default application, Cyberduck will open when you click on FTP or SFTP links in other applications, such as your web browser. You can change this setting in the Preferences later.", "Configuration"),
Locale.localizedString("Change", "Configuration"), //default
null, //other
Locale.localizedString("Cancel", "Configuration"));
alert.setAlertStyle(NSAlert.NSInformationalAlertStyle);
alert.setShowsSuppressionButton(true);
alert.suppressionButton().setTitle(Locale.localizedString("Don't ask again", "Configuration"));
int choice = alert.runModal(); //alternate
if(alert.suppressionButton().state() == NSCell.NSOnState) {
// Never show again.
Preferences.instance().setProperty("defaulthandler.reminder", false);
}
if(choice == SheetCallback.DEFAULT_OPTION) {
URLSchemeHandlerConfiguration.instance().setDefaultHandlerForURLScheme(
new String[]{Protocol.FTP.getScheme(), Protocol.FTP_TLS.getScheme(), Protocol.SFTP.getScheme()},
NSBundle.mainBundle().infoDictionary().objectForKey("CFBundleIdentifier").toString()
);
}
}
}
// NSWorkspace notifications are posted to a notification center provided by
// the NSWorkspace object, instead of going through the application’s default
// notification center as most notifications do. To receive NSWorkspace notifications,
// your application must register an observer with the NSWorkspace notification center.
NSWorkspace.sharedWorkspace().notificationCenter().addObserver(this.id(),
Foundation.selector("workspaceWillPowerOff:"),
NSWorkspace.WorkspaceWillPowerOffNotification,
null);
NSWorkspace.sharedWorkspace().notificationCenter().addObserver(this.id(),
Foundation.selector("workspaceWillLogout:"),
NSWorkspace.WorkspaceSessionDidResignActiveNotification,
null);
NSWorkspace.sharedWorkspace().notificationCenter().addObserver(this.id(),
Foundation.selector("workspaceWillSleep:"),
NSWorkspace.WorkspaceWillSleepNotification,
null);
NSNotificationCenter.defaultCenter().addObserver(this.id(),
Foundation.selector("applicationWillRestartAfterUpdate:"),
"SUUpdaterWillRestartNotificationName",
null);
if(Preferences.instance().getBoolean("rendezvous.enable")) {
this.background(new AbstractBackgroundAction() {
public void run() {
RendezvousFactory.instance().init();
}
});
}
// Import thirdparty bookmarks.
this.background(new AbstractBackgroundAction() {
private List<ThirdpartyBookmarkCollection> bookmarks = Collections.emptyList();
public void run() {
bookmarks = this.getThirdpartyBookmarks();
for(ThirdpartyBookmarkCollection c : bookmarks) {
if(!Preferences.instance().getBoolean(c.getConfiguration())) {
if(!c.isInstalled()) {
log.info("No application installed for " + c.getBundleIdentifier());
continue;
}
c.load();
if(c.isEmpty()) {