-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy path__init__.py
2165 lines (1989 loc) · 65.5 KB
/
__init__.py
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
from core.commands.util import get_program_files, get_program_files_x86, \
is_hidden
from core.fileoperations import CopyFiles, MoveFiles
from core.github import find_repos, GitHubRepo
from core.os_ import open_terminal_in_directory, open_native_file_manager, \
get_popen_kwargs_for_opening
from core.util import strformat_dict_values, listdir_absolute, is_parent
from core.quicksearch_matchers import contains_chars, \
contains_chars_after_separator
from fman import *
from fman.fs import exists, touch, mkdir, is_dir, delete, samefile, copy, \
iterdir, resolve, prepare_copy, prepare_move, prepare_delete, \
FileSystem, prepare_trash, query, makedirs, notify_file_added
from fman.impl.util import get_user
from fman.url import splitscheme, as_url, join, basename, as_human_readable, \
dirname, relpath, normalize
from io import UnsupportedOperation
from itertools import chain
from os import strerror
from os.path import basename, pardir
from pathlib import PurePath
from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QDesktopServices
from subprocess import Popen, DEVNULL, PIPE
from tempfile import TemporaryDirectory
from urllib.error import URLError
import errno
import fman.fs
import json
import os
import os.path
import re
import sys
from .goto import *
class About(ApplicationCommand):
def __call__(self):
msg = "fman version: " + FMAN_VERSION
msg += "\n" + self._get_registration_info()
show_alert(msg)
def _get_registration_info(self):
user_json_path = os.path.join(DATA_DIRECTORY, 'Local', 'User.json')
try:
with open(user_json_path, 'r') as f:
data = json.load(f)
return 'Registered to %s.' % data['email']
except (FileNotFoundError, ValueError, KeyError):
return 'Not registered.'
class Help(ApplicationCommand):
aliases = ('Help', 'Show keyboard shortcuts', 'Show key bindings')
def __call__(self):
QDesktopServices.openUrl(QUrl('https://fman.io/docs/key-bindings?s=f'))
class MoveCursorDown(DirectoryPaneCommand):
def __call__(self, toggle_selection=False):
self.pane.move_cursor_down(toggle_selection)
class MoveCursorUp(DirectoryPaneCommand):
def __call__(self, toggle_selection=False):
self.pane.move_cursor_up(toggle_selection)
class MoveCursorHome(DirectoryPaneCommand):
def __call__(self, toggle_selection=False):
self.pane.move_cursor_home(toggle_selection)
class MoveCursorEnd(DirectoryPaneCommand):
def __call__(self, toggle_selection=False):
self.pane.move_cursor_end(toggle_selection)
class MoveCursorPageUp(DirectoryPaneCommand):
def __call__(self, toggle_selection=False):
self.pane.move_cursor_page_up(toggle_selection)
class MoveCursorPageDown(DirectoryPaneCommand):
def __call__(self, toggle_selection=False):
self.pane.move_cursor_page_down(toggle_selection)
class ToggleSelection(DirectoryPaneCommand):
def __call__(self):
file_under_cursor = self.pane.get_file_under_cursor()
if file_under_cursor:
self.pane.toggle_selection(file_under_cursor)
class MoveToTrash(DirectoryPaneCommand):
aliases = ('Delete', 'Move to trash', 'Move to recycle bin')
def __call__(self, urls=None):
if urls is None:
urls = self.get_chosen_files()
if not urls:
show_alert('No file is selected!')
return
description = _describe(urls, 'these %d files')
trash = 'Recycle Bin' if PLATFORM == 'Windows' else 'Trash'
msg = "Do you really want to move %s to the %s?" % (description, trash)
if show_alert(msg, YES | NO, YES) & YES:
submit_task(_Delete(urls, prepare_trash, prepare_delete))
def is_visible(self):
return bool(self.pane.get_file_under_cursor())
class DeletePermanently(DirectoryPaneCommand):
def __call__(self, urls=None):
if urls is None:
urls = self.get_chosen_files()
if not urls:
show_alert('No file is selected!')
return
description = _describe(urls, 'these %d items')
message = \
"Do you really want to PERMANENTLY delete %s? This action cannot " \
"be undone!" % description
if show_alert(message, YES | NO, YES) & YES:
submit_task(_Delete(urls, prepare_delete))
class _Delete(Task):
def __init__(self, urls, prepare_fn, fallback=None):
super().__init__('Deleting ' + _describe(urls))
self._urls = urls
self._num_urls_prepared = 0
self._prepare_fn = prepare_fn
self._fallback = fallback
self._tasks = []
def __call__(self):
try:
self._gather_tasks()
except (UnsupportedOperation, NotImplementedError):
failing_url = self._urls[self._num_urls_prepared]
self.show_alert(
'Deleting files in %s is not supported.'
% splitscheme(failing_url)[0]
)
return
ignore_errors = False
for i, task in enumerate(self._tasks):
self.check_canceled()
try:
self.run(task)
except FileNotFoundError:
# Perhaps the file has already been deleted.
pass
except OSError as e:
if ignore_errors:
continue
text = task.get_title()
message = 'Error ' + text[0].lower() + text[1:]
reason = e.strerror or ''
if not reason and e.errno is not None:
reason = strerror(e.errno)
if reason:
message += ': ' + reason
message += '.'
is_last = i == len(self._tasks) - 1
if is_last:
self.show_alert(message)
else:
message += ' Do you want to continue?'
choice = show_alert(message, YES | NO | YES_TO_ALL)
if choice & NO:
break
if choice & YES_TO_ALL:
ignore_errors = True
def _gather_tasks(self):
for url in self._urls:
try:
self._prepare(url, self._prepare_fn)
except (NotImplementedError, UnsupportedOperation):
if self._fallback is None:
raise
self._prepare(url, self._fallback)
self._num_urls_prepared += 1
self.set_size(sum(t.get_size() for t in self._tasks))
def _prepare(self, url, prepare_fn):
url_tasks = []
for task in prepare_fn(url):
self.check_canceled()
url_tasks.append(task)
if task.get_size():
num = len(self._tasks) + len(url_tasks)
self.set_text('Preparing to delete {:,} files.'.format(num))
self._tasks.extend(url_tasks)
def _describe(files, template='%d files'):
if len(files) == 1:
return basename(files[0])
return template % len(files)
class GoUp(DirectoryPaneCommand):
aliases = ('Go up', 'Go to parent directory')
def __call__(self):
go_up(self.pane)
def go_up(pane):
path_before = pane.get_path()
def callback():
path_now = pane.get_path()
# Only move the cursor if we actually changed directories; For
# instance, we don't want to move the cursor if the user presses
# Backspace while at drives:// and the cursor is already at
# drives://C:
if path_now != path_before:
# Consider: The user is in zip:///Temp.zip and invokes GoUp.
# This takes us to file:///. We want to place the cursor at
# file:///Temp.zip. "Switch" schemes to make this happen:
cursor_dest = splitscheme(path_now)[0] + \
splitscheme(path_before)[1]
try:
pane.place_cursor_at(cursor_dest)
except ValueError as dest_doesnt_exist:
pane.move_cursor_home()
parent_dir = dirname(path_before)
try:
pane.set_path(parent_dir, callback)
except FileNotFoundError:
# This for instance happens when the user pressed backspace when at
# file:/// on Unix.
pass
class Open(DirectoryPaneCommand):
def __call__(self, url=None):
if url is None:
url = self.pane.get_file_under_cursor()
if url:
try:
url_is_dir = is_dir(url)
except OSError as e:
show_alert(
'Could not read from %s (%s)' % (as_human_readable(url), e)
)
return
# Use `run_command` to delegate the actual opening. This makes it
# possible for plugins to modify the default open behaviour by
# implementing DirectoryPaneListener#on_command(...).
if url_is_dir:
if PLATFORM == 'Mac' and url.endswith('.app'):
dialogs = load_json('Core Dialogs.json', default={})
if not dialogs.get('open_app_hint_shown', False):
show_alert(
'Quick tip: Apps in macOS are directories. When '
'you press '
'<span style="color: white;">Enter</span>, '
'fman therefore browses them. If you want to '
'launch the app instead, press '
'<span style="color: white;">Cmd+Enter</span>.'
)
dialogs['open_app_hint_shown'] = True
save_json('Core Dialogs.json')
return
self.pane.run_command('open_directory', {'url': url})
else:
self.pane.run_command('open_file', {'url': url})
else:
show_alert('No file is selected!')
class OpenListener(DirectoryPaneListener):
def on_doubleclicked(self, file_url):
self.pane.run_command('open', {'url': file_url})
class OpenDirectory(DirectoryPaneCommand):
def __call__(self, url):
try:
url_is_dir = is_dir(url)
except OSError as e:
show_alert(
'Could not read from %s (%s)' % (as_human_readable(url), e)
)
return
if url_is_dir:
try:
self.pane.set_path(url, onerror=None)
except PermissionError:
show_alert(
'Access to "%s" was denied.' % as_human_readable(url)
)
else:
def callback():
try:
self.pane.place_cursor_at(url)
except ValueError as file_disappeared:
pass
self.pane.set_path(dirname(url), callback=callback, onerror=None)
def is_visible(self):
return False
class OpenFile(DirectoryPaneCommand):
def __call__(self, url):
_open_files([url], self.pane)
def is_visible(self):
return False
def _open_files(urls, pane):
local_file_paths = []
for url in urls:
# On Windows, CMD can handle mapped drives Z:\ but not UNC paths
# //192.168.0.2. If the former maps to the latter, then CMD fails to
# run .bat files in that location. So only resolve if absolutely
# necessary, i.e. when not a file:// URL:
if not _is_file_url(url):
try:
url = resolve(url)
except FileNotFoundError:
# No sense to try to open a file that does not exist.
continue
except OSError as e:
# Not all OSErrors need prevent us from opening the file.
# So only skip this file if it does not exist:
if e.errno == errno.ENOENT:
continue
scheme = splitscheme(url)[0]
if scheme != 'file://':
show_alert(
'Opening files from %s is not supported. If you are a plugin '
'developer, you can implement this with '
'DirectoryPaneListener#on_command(...).' % scheme
)
return
# Use as_human_readable(...) instead of the result from splitscheme(...)
# above to get backslashes on Windows:
local_file_paths.append(as_human_readable(url))
_open_local_files(local_file_paths, pane)
def _is_file_url(url):
return splitscheme(url)[0] == 'file://'
def _open_local_files(paths, pane):
if PLATFORM == 'Windows':
_open_local_files_win(paths, pane)
elif PLATFORM == 'Mac':
_open_local_files_mac(paths)
else:
assert PLATFORM == 'Linux'
_open_local_files_linux(paths)
def _open_local_files_win(paths, pane):
# Whichever implementation is used here, it should support:
# * C:\picture.jpg
# * C:\notepad.exe
# * C:\a & b.txt
# * C:\batch.bat should print the current dir:
# echo %cd%
# pause
# * \\server\share\picture.jpg
# * D:\Book.pdf
# * \\cryptomator-vault\app.exe
for path in paths:
if path.endswith('.lnk'):
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut(path)
target_url = as_url(shortcut.TargetPath)
if is_dir(target_url):
pane.set_path(target_url)
return
try:
from win32api import ShellExecute
from win32con import SW_SHOWNORMAL
cwd = os.path.dirname(path)
ShellExecute(0, None, path, None, cwd, SW_SHOWNORMAL)
except OSError:
# This for instance happens when the file is an .exe that requires
# Admin privileges, but the user cancels the UAC "do you want to run
# this file?" dialog.
pass
def _open_local_files_mac(paths):
non_executables = []
for path in paths:
try:
_run_executable(path)
except (OSError, ValueError):
non_executables.append(path)
if non_executables:
try:
Popen(['open'] + non_executables, **_quiet)
except OSError:
pass
def _open_local_files_linux(paths):
for path in paths:
try:
_run_executable(path)
except (OSError, ValueError):
try:
Popen(['xdg-open', path], **_quiet)
except Exception as e:
raise e from None
def _run_executable(path):
Popen([path], cwd=os.path.dirname(path), **_quiet)
_quiet = {'stdout': DEVNULL, 'stderr': DEVNULL}
class OpenSelectedFiles(DirectoryPaneCommand):
def __call__(self):
file_under_cursor = self.pane.get_file_under_cursor()
selected_files = self.pane.get_selected_files()
if file_under_cursor in selected_files:
_open_files(selected_files, self.pane)
else:
_open_files([file_under_cursor], self.pane)
def is_visible(self):
return bool(self.get_chosen_files())
class OpenWithEditor(DirectoryPaneCommand):
aliases = ('Edit',)
def __call__(self, url=None):
if url is None:
url = self.pane.get_file_under_cursor()
if not url:
show_alert('No file is selected!')
return
url = resolve(url)
scheme = splitscheme(url)[0]
if scheme != 'file://':
show_alert(
'Editing files from %s is not supported. If you are a plugin '
'developer, you can implement this with '
'DirectoryPaneListener#on_command(...).' % scheme
)
return
editor = self._get_editor()
if editor:
file_path = as_human_readable(url)
popen_kwargs = strformat_dict_values(editor, {'file': file_path})
Popen(**popen_kwargs)
def _get_editor(self):
settings = load_json('Core Settings.json', default={})
result = settings.get('editor', {})
if result:
try:
executable_path = result['args'][0]
except (KeyError, IndexError, TypeError):
pass
else:
if os.path.exists(executable_path):
return result
message = 'Could not find your editor. Please select it again.'
else:
message = 'Editor is currently not configured. Please pick one.'
choice = show_alert(message, OK | CANCEL, OK)
if choice & OK:
editor_path = _show_app_open_dialog('Pick an Editor')
if editor_path:
result = get_popen_kwargs_for_opening(['{file}'], editor_path)
settings['editor'] = result
save_json('Core Settings.json')
return result
return {}
def _show_app_open_dialog(caption):
return show_file_open_dialog(
caption, _get_applications_directory(),
_PLATFORM_APPLICATIONS_FILTER[PLATFORM]
)
_PLATFORM_APPLICATIONS_FILTER = {
'Mac': 'Applications (*.app)',
'Windows': 'Applications (*.exe)',
'Linux': 'Applications (*)'
}
def _get_applications_directory():
if PLATFORM == 'Mac':
return '/Applications'
elif PLATFORM == 'Windows':
result = get_program_files()
if not os.path.exists(result):
result = get_program_files_x86()
if not os.path.exists(result):
result = PurePath(sys.executable).anchor
return result
elif PLATFORM == 'Linux':
return '/usr/bin'
raise NotImplementedError(PLATFORM)
class CreateAndEditFile(OpenWithEditor):
aliases = ('New file', 'Create file', 'Create and edit file')
def __call__(self, url=None):
file_under_cursor = self.pane.get_file_under_cursor()
default_name = ''
if file_under_cursor:
try:
file_is_dir = is_dir(file_under_cursor)
except OSError:
file_is_dir = False
if not file_is_dir:
default_name = basename(file_under_cursor)
selection_end = _find_extension_start(default_name)
file_name, ok = show_prompt(
'Enter file name to create/edit:', default_name,
selection_end=selection_end
)
if ok and file_name:
file_to_edit = join(self.pane.get_path(), file_name)
if not exists(file_to_edit):
try:
touch(file_to_edit)
except PermissionError:
show_alert(
"You do not have enough permissions to create %s."
% as_human_readable(file_to_edit)
)
return
except NotImplementedError:
show_alert(
'Sorry, creating a file for editing is not supported '
'here.'
)
return
try:
self.pane.place_cursor_at(file_to_edit)
except ValueError:
# This can happen when the file is hidden. Eg .bashrc on Linux.
pass
super().__call__(file_to_edit)
def _find_extension_start(file_name, start=0):
for dual_extension in ('.pkg.tar.xz', '.tar.xz', '.tar.gz'):
if file_name.endswith(dual_extension):
return len(file_name) - len(dual_extension)
try:
return file_name.rindex('.', start)
except ValueError as not_found:
return None
class _TreeCommand(DirectoryPaneCommand):
def __call__(self, files=None, dest_dir=None):
if files is None:
files = self.get_chosen_files()
src_dir = self.pane.get_path()
else:
# This for instance happens in Drag and Drop operations.
src_dir = None
if dest_dir is None:
dest_dir = _get_opposite_pane(self.pane).get_path()
proceed = self._confirm_tree_operation(files, dest_dir, src_dir)
if proceed:
dest_dir, dest_name = proceed
makedirs(dest_dir, exist_ok=True)
self._call(files, dest_dir, dest_name)
def _call(self, files, dest_dir, dest_name=None):
raise NotImplementedError()
@classmethod
def _confirm_tree_operation(
cls, files, dest_dir, src_dir, ui=fman, fs=fman.fs
):
if not files:
ui.show_alert('No file is selected!')
return
selection_start = 0
selection_end = None # Select everything
if len(files) == 1:
file_, = files
dest_name = basename(file_)
files_descr = '"%s"' % dest_name
try:
exists_and_is_dir = fs.is_dir(file_)
except FileNotFoundError:
exists_and_is_dir = False
except OSError as e:
ui.show_alert(
'Could not read from %s (%s)' %
(as_human_readable(file_), e)
)
return
if exists_and_is_dir:
"""
There is only one reasonable course of action when the file to
be copied is a dir: Suggest the parent directory and copy the
dir into it as a folder. The alternative would be to suggest the
destination directory and copy the dir's *contents*. But this
brings a host of problems: Say we copy folder src/ to (inside)
dst/ once, and then a second time. Then src/dst is suggested. It
already exists. This leads to the remaining logic in this class
copying to src/dst/dst instead of overwriting the previously
copied files.
Another problem with the alternative approach would be that the
user may copy a folder with a lot of files, and manually type in
an existing destination directory. If we copied the folder's
contents, then the user may end up with thousands of files
scattered all over the existing directory when he intended for
them to be contained in a separate, single directory.
Finally, the alternative approach might not be able to preserve
the directory's permissions when an existing destination folder
is supplied.
"""
suggested_dst = as_human_readable(dest_dir)
else:
dest_url = join(dest_dir, dest_name)
suggested_dst, selection_start, selection_end = \
get_dest_suggestion(dest_url)
else:
files_descr = '%d files' % len(files)
suggested_dst = as_human_readable(dest_dir)
message = '%s %s to' % (cls._verb().capitalize(), files_descr)
dest, ok = ui.show_prompt(
message, suggested_dst, selection_start, selection_end
)
if dest and ok:
dest_url = _from_human_readable(dest, dest_dir, src_dir)
if fs.exists(dest_url):
try:
dest_is_dir = fs.is_dir(dest_url)
except OSError as e:
ui.show_alert('Could not read from %s (%s)' % (dest, e))
return
if dest_is_dir:
if len(files) == 1 and fs.samefile(dest_url, files[0]):
# This happens when renaming a/ -> A/ on
# case-insensitive file systems.
return _split(dest_url)
for file_ in files:
if is_parent(file_, dest_url, fs):
ui.show_alert(
'You cannot %s a file to itself!' % cls._verb()
)
return
return dest_url, None
else:
if len(files) == 1:
return _split(dest_url)
else:
ui.show_alert(
'You cannot %s multiple files to a single file!' %
cls._verb()
)
else:
if len(files) == 1:
return _split(dest_url)
else:
choice = ui.show_alert(
'%s does not exist. Do you want to create it '
'as a directory and %s the files there?' %
(as_human_readable(dest_url), cls._verb()),
YES | NO, YES
)
if choice & YES:
return dest_url, None
@classmethod
def _verb(cls):
return cls.__name__.lower()
def is_visible(self):
return bool(self.pane.get_file_under_cursor())
def get_dest_suggestion(dst_url):
scheme = splitscheme(dst_url)[0]
if scheme == 'file://':
sep = os.sep
suggested_dst = as_human_readable(dst_url)
offset = 0
else:
sep = '/'
suggested_dst = dst_url
offset = len(scheme)
try:
last_sep = suggested_dst.rindex(sep, offset)
except ValueError as no_sep:
selection_start = offset
else:
selection_start = last_sep + 1
selection_end = _find_extension_start(suggested_dst, selection_start)
return suggested_dst, selection_start, selection_end
def _get_opposite_pane(pane):
panes = pane.window.get_panes()
return panes[(panes.index(pane) + 1) % len(panes)]
def _from_human_readable(path_or_url, dest_dir, src_dir):
try:
splitscheme(path_or_url)
except ValueError as no_scheme:
dest_scheme, dest_dir_path = splitscheme(dest_dir)
if src_dir:
# Treat dest as relative to src_dir:
src_scheme, src_path = splitscheme(src_dir)
dest_path = PurePath(src_path, path_or_url).as_posix()
else:
dest_path = PurePath(dest_dir_path, path_or_url).as_posix()
path_or_url = dest_scheme + dest_path
return path_or_url
def _split(url):
scheme, tail = splitscheme(url)
head, tail = re.match('(/*)(.*?)$', tail).groups()
if '/' in tail:
h2, tail = tail.rsplit('/', 1)
head += h2
return scheme + head, tail
class Copy(_TreeCommand):
def _call(self, files, dest_dir, dest_name=None):
submit_task(CopyFiles(files, dest_dir, dest_name))
class Move(_TreeCommand):
def _call(self, files, dest_dir, dest_name=None):
submit_task(MoveFiles(files, dest_dir, dest_name))
class DragAndDropListener(DirectoryPaneListener):
def on_files_dropped(self, file_urls, dest_dir, is_copy_not_move):
command = self._get_command(file_urls, dest_dir, is_copy_not_move)
self.pane.run_command(
command, {'files': file_urls, 'dest_dir': dest_dir}
)
def _get_command(self, file_urls, dest_dir, is_copy_not_move):
schemes = set(splitscheme(url)[0] for url in file_urls)
src_scheme = next(iter(schemes)) if len(schemes) == 1 else ''
dest_scheme = splitscheme(dest_dir)[0]
if src_scheme != dest_scheme:
# The default value for `is_copy_not_move` is False. But consider
# the case where the user drags a file from a Zip archive to the
# local file system. In this case, `is_copy_not_move` might indicate
# "move" simply because it's the default. But most likely, the user
# simply wants to extract the file and not also remove it from the
# Zip file. Respect this:
is_copy_not_move = True
return 'copy' if is_copy_not_move else 'move'
class Symlink(_TreeCommand):
aliases = ('Symlink', 'Create symbolic link')
def is_visible(self):
if not super().is_visible():
return False
return _is_file_url(self.pane.get_path()) and \
_is_file_url(_get_opposite_pane(self.pane).get_path())
def __call__(self):
src_url = self.pane.get_path()
if not _is_file_url(src_url):
self._refuse()
return
dest_url = _get_opposite_pane(self.pane).get_path()
if not _is_file_url(dest_url):
self._refuse()
return
super().__call__()
def _call(self, files, dest_dir, dest_name=None):
ignore_exists = False
for i, f_url in enumerate(files):
dest_url = join(dest_dir, dest_name or basename(f_url))
if not _is_file_url(f_url) or not _is_file_url(dest_url):
self._refuse()
return
f_path = as_human_readable(f_url)
dest_path = as_human_readable(dest_url)
try:
os.symlink(f_path, dest_path, is_dir(f_url))
except FileExistsError:
if ignore_exists:
continue
has_more = i < len(files) - 1
if has_more:
answer = show_alert(
"%s exists and cannot be symlinked. Continue?"
% basename(f_url),
YES | NO | YES_TO_ALL, YES
)
if answer & YES_TO_ALL:
ignore_exists = True
elif answer & NO:
break
else:
show_alert(
"%s exists and cannot be symlinked." % basename(f_url)
)
else:
notify_file_added(dest_url)
def _refuse(self):
show_alert('Sorry, can only create symlinks between local files.')
class Rename(DirectoryPaneCommand):
def __call__(self):
file_under_cursor = self.pane.get_file_under_cursor()
if file_under_cursor:
try:
file_is_dir = is_dir(file_under_cursor)
except OSError as e:
show_alert(
'Could not read from %s (%s)' %
(as_human_readable(file_under_cursor), e)
)
return
if file_is_dir:
selection_end = None
else:
file_name = basename(file_under_cursor)
selection_end = _find_extension_start(file_name)
self.pane.edit_name(file_under_cursor, selection_end=selection_end)
else:
show_alert('No file is selected!')
def is_visible(self):
return bool(self.pane.get_file_under_cursor())
class RenameListener(DirectoryPaneListener):
def on_name_edited(self, file_url, new_name):
old_name = basename(file_url)
if not new_name or new_name == old_name:
return
is_relative = \
os.sep in new_name or new_name in (pardir, '.') \
or (PLATFORM == 'Windows' and '/' in new_name)
if is_relative:
show_alert(
'Relative paths are not supported. Please use Move (F6) '
'instead.'
)
return
new_url = join(dirname(file_url), new_name)
if exists(new_url):
# Don't show dialog when "Foo" was simply renamed to "foo":
if not samefile(new_url, file_url):
show_alert(new_name + ' already exists!')
return
submit_task(_Rename(self.pane, file_url, new_url))
class _Rename(Task):
def __init__(self, pane, src_url, dst_url):
self._pane = pane
self._src_url = src_url
self._dst_url = dst_url
super().__init__('Renaming ' + basename(src_url))
def __call__(self):
self.set_text('Preparing...')
tasks = list(prepare_move(self._src_url, self._dst_url))
self.set_size(sum(t.get_size() for t in tasks))
try:
for task in tasks:
self.check_canceled()
self.run(task)
except OSError as e:
if isinstance(e, PermissionError):
message = 'Access was denied trying to rename %s to %s.'
else:
message = 'Could not rename %s to %s.'
old_name = basename(self._src_url)
new_name = basename(self._dst_url)
self.show_alert(message % (old_name, new_name))
else:
try:
self._pane.place_cursor_at(self._dst_url)
except ValueError as file_disappeared:
pass
class CreateDirectory(DirectoryPaneCommand):
aliases = (
'New folder', 'Create folder', 'New directory', 'Create directory'
)
def __call__(self):
file_under_cursor = self.pane.get_file_under_cursor()
if file_under_cursor:
default = basename(file_under_cursor).split('.', 1)[0]
else:
default = ''
name, ok = show_prompt("New folder (directory)", default)
if ok and name:
# Support recursive creation of directories:
if PLATFORM == 'Windows':
name = name.replace('\\', '/')
base_url = self.pane.get_path()
dir_url = join(base_url, name)
try:
makedirs(dir_url)
except FileExistsError:
show_alert("A file with this name already exists!")
# Use normalize(...) instead of resolve(...) to avoid the following
# problem: Say c/ is a symlink to a/b/. We're inside c/ and create
# d. Then # resolve(c/d) would give a/b/d and the relative path
# further down # would be ../a/b/d. We could not place the cursor at
# that. If on # the other hand, we use normalize(...), then we
# compute the relpath from c -> c/d, which does work.
effective_url = normalize(dir_url)
select = relpath(effective_url, base_url).split('/')[0]
if select != '..':
try:
self.pane.place_cursor_at(join(base_url, select))
except ValueError as dir_disappeared:
pass
def is_visible(self):
fs = splitscheme(self.pane.get_path())[0]
return _fs_implements(fs, 'mkdir')
def _fs_implements(scheme, method_name):
# Using query(...) in this way is quite hacky, but works:
method = query(scheme + method_name, '__getattr__')
return method.__func__ is not getattr(FileSystem, method_name)
class OpenTerminal(DirectoryPaneCommand):
aliases = (
'Terminal', 'Shell', 'Open terminal', 'Open shell'
)
def __call__(self):
scheme, path = splitscheme(self.pane.get_path())
if scheme != 'file://':
show_alert(
"Can currently open the terminal only in local directories."
)
return
open_terminal_in_directory(path)
class OpenNativeFileManager(DirectoryPaneCommand):
def __call__(self):
url = self.pane.get_path()
scheme = splitscheme(url)[0]
if scheme != 'file://':
if PLATFORM == 'Mac':
native_fm = 'Finder'
elif PLATFORM == 'Windows':
native_fm = 'Explorer'
else:
native_fm = 'your native file manager'
show_alert("Cannot open %s in %s" % (native_fm, scheme))
return
open_native_file_manager(as_human_readable(url))
class CopyPathsToClipboard(DirectoryPaneCommand):
def __call__(self):
to_copy = self.get_chosen_files() or [self.pane.get_path()]
files = '\n'.join(to_copy)
clipboard.clear()
clipboard.set_text('\n'.join(map(as_human_readable, to_copy)))
_report_clipboard_action('Copied', to_copy, ' to the clipboard', 'path')
def _report_clipboard_action(verb, files, suffix='', ftype='file'):
num = len(files)
first_file = as_human_readable(files[0])
if num == 1:
message = '%s %s%s' % (verb, first_file, suffix)
else:
plural = 's' if num > 2 else ''
message = '%s %s and %d other %s%s%s' % \
(verb, first_file, num - 1, ftype, plural, suffix)
show_status_message(message, timeout_secs=3)
class CopyToClipboard(DirectoryPaneCommand):
def __call__(self):
files = self.get_chosen_files()
if files:
clipboard.copy_files(files)
_report_clipboard_action('Copying', files)
else:
show_alert('No file is selected!')
def is_visible(self):
return bool(self.pane.get_file_under_cursor())
class Cut(DirectoryPaneCommand):
def __call__(self):
if PLATFORM == 'Mac':
show_alert(
"Sorry, macOS doesn't support cutting files. Please press "
"⌘-C (copy) followed by ⌘-⌥-V (move)."
)
return
files = self.get_chosen_files()
if files:
clipboard.cut_files(files)
_report_clipboard_action('Cutting', files)
else:
show_alert('No file is selected!')
def is_visible(self):
return bool(self.pane.get_file_under_cursor())
class Paste(DirectoryPaneCommand):
def __call__(self):
files = clipboard.get_files()
if not files:
return
if clipboard.files_were_cut():
self.pane.run_command('paste_cut')
else:
dest = self.pane.get_path()
self.pane.run_command('copy', {'files': files, 'dest_dir': dest})
def is_visible(self):
return bool(clipboard.get_files())
class PasteCut(DirectoryPaneCommand):
def __call__(self):
files = clipboard.get_files()
if not any(map(exists, files)):
# This can happen when the paste-cut has already been performed.
return