forked from thonny/thonny
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase_file_browser.py
More file actions
1914 lines (1558 loc) · 63.7 KB
/
Copy pathbase_file_browser.py
File metadata and controls
1914 lines (1558 loc) · 63.7 KB
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
import os.path
import shutil
import time
import tkinter as tk
from abc import ABC
from logging import getLogger
from tkinter import messagebox, simpledialog, ttk
from typing import Any, Dict, List, Optional, Tuple
from pystart import get_runner, get_workbench, misc_utils, tktextext
from pystart.common import InlineCommand, UserError, get_dirs_children_info
from pystart.languages import tr
from pystart.misc_utils import (
format_date_and_time_compact,
get_menu_char,
get_os_level_favorite_folders,
is_local_project_dir,
is_local_venv_dir,
running_on_windows,
sizeof_fmt,
)
from pystart.ui_utils import (
CommonDialog,
CustomToolbutton,
MappingCombobox,
ask_one_from_choices,
ask_string,
check_create_aqua_scrollbar_stripe,
create_action_label,
create_string_var,
ems_to_pixels,
get_hyperlink_cursor,
lookup_style_option,
open_with_default_app,
pixels_to_ems,
show_dialog,
)
_dummy_node_text = "..."
_LOCAL_FILES_ROOT_TEXT = "" # needs to be initialized later
ROOT_NODE_ID = ""
HIDDEN_FILES_OPTION = "file.show_hidden_files"
FILE_DIALOG_ORDER_BY_OPTION = "file.dialog_order_by"
FILE_DIALOG_REVERSE_ORDER_OPTION = "file.dialog_reverse_order"
FILE_DIALOG_WIDTH_EMS_OPTION = "file.dialog_width_ems"
FILE_DIALOG_HEIGHT_EMS_OPTION = "file.dialog_height_ems"
logger = getLogger(__name__)
class BaseFileBrowser(ttk.Frame):
def __init__(
self, master, show_expand_buttons=True, order_by: str = "name", reverse_order: bool = False
):
self.show_expand_buttons = show_expand_buttons
self._cached_child_data: Dict[str, Dict[str, Any]] = {}
self.path_to_highlight = None
self.order_by = order_by
self.reverse_order = reverse_order
self.filter: Optional[List[str]] = None
ttk.Frame.__init__(self, master, borderwidth=0, relief="flat")
self.vert_scrollbar = ttk.Scrollbar(self, orient=tk.VERTICAL)
self.vert_scrollbar.grid(row=0, column=1, sticky=tk.NSEW, rowspan=3)
stripe = check_create_aqua_scrollbar_stripe(self)
if stripe is not None:
stripe.grid(row=0, column=1, sticky="nse", rowspan=3)
stripe.tkraise()
tktextext.fixwordbreaks(tk._default_root)
self.building_breadcrumbs = False
self.init_header(row=0, column=0)
spacer = ttk.Frame(self, height=1)
spacer.grid(row=1, sticky="nsew")
self.tree = ttk.Treeview(
self,
columns=[
"#0",
"kind",
"path",
"name",
"modified_fmt",
"size_fmt",
"modified_epoch",
"size_bytes",
],
displaycolumns=(
# 4,
# 5
),
yscrollcommand=self.vert_scrollbar.set,
selectmode="extended",
)
self.tree.tag_configure("project", font="BoldTkDefaultFont")
self.tree.tag_configure("venv", font="ItalicTkDefaultFont")
self.tree.grid(row=2, column=0, sticky=tk.NSEW)
self.vert_scrollbar["command"] = self.tree.yview
self.columnconfigure(0, weight=1)
self.rowconfigure(2, weight=1)
self.tree["show"] = "tree"
self.tree.bind("<3>", self.on_secondary_click, True)
if misc_utils.running_on_mac_os():
self.tree.bind("<2>", self.on_secondary_click, True)
self.tree.bind("<Control-1>", self.on_secondary_click, True)
self.tree.bind("<Double-Button-1>", self.on_double_click, True)
self.tree.bind("<<TreeviewOpen>>", self.on_open_node)
self.copypaste = None
wb = get_workbench()
self.folder_icon = wb.get_image("folder")
self.python_file_icon = wb.get_image("python-icon")
self.text_file_icon = wb.get_image("text-file")
self.generic_file_icon = wb.get_image("generic-file")
self.hard_drive_icon = wb.get_image("hard-drive")
self.tree.column("#0", width=200, anchor=tk.W)
self.tree.heading(
"#0", text=tr("Name"), anchor=tk.W, command=lambda: self.on_heading_click("name")
)
self.tree.column("modified_fmt", width=60, anchor=tk.E)
self.tree.heading(
"modified_fmt",
text=tr("Modified"),
anchor=tk.E,
command=lambda: self.on_heading_click("modified"),
)
self.tree.column("size_fmt", width=40, anchor=tk.E)
self.tree.heading(
"size_fmt", text=tr("Size"), anchor=tk.E, command=lambda: self.on_heading_click("size")
)
self._update_heading_labels()
# set-up root node
self.tree.set(ROOT_NODE_ID, "kind", "root")
self.menu = tk.Menu(self.tree, tearoff=False)
self.current_focus = None
self._on_theme_changed_binding = self.bind("<<ThemeChanged>>", self.on_theme_changed, True)
def init_header(self, row, column):
header_frame = ttk.Frame(self, style="ViewToolbar.TFrame")
header_frame.grid(row=row, column=column, sticky="nsew")
header_frame.columnconfigure(0, weight=1)
self.path_bar = tktextext.TweakableText(
header_frame,
borderwidth=0,
relief="flat",
height=1,
font="TkDefaultFont",
wrap="word",
padx=ems_to_pixels(0.6),
pady=ems_to_pixels(0.5),
insertwidth=0,
highlightthickness=0,
background=self.get_path_bar_background(),
foreground=self.get_label_foreground(),
)
self.path_bar.grid(row=0, column=0, sticky="nsew")
self.path_bar.set_read_only(True)
self.path_bar.bind("<Configure>", self.resize_path_bar, True)
self.path_bar.tag_configure("dir", foreground=self.get_url_foreground())
self.path_bar.tag_configure("project", font="BoldTkDefaultFont")
self.path_bar.tag_configure("venv", font="ItalicTkDefaultFont")
self.path_bar.tag_configure("underline", underline=True)
def get_dir_range(event):
mouse_index = self.path_bar.index("@%d,%d" % (event.x, event.y))
return self.path_bar.tag_prevrange("dir", mouse_index + "+1c")
def dir_tag_motion(event):
self.path_bar.tag_remove("underline", "1.0", "end")
dir_range = get_dir_range(event)
if dir_range:
range_start, range_end = dir_range
self.path_bar.tag_add("underline", range_start, range_end)
def dir_tag_enter(event):
self.path_bar.config(cursor=get_hyperlink_cursor())
def dir_tag_leave(event):
self.path_bar.config(cursor="")
self.path_bar.tag_remove("underline", "1.0", "end")
def dir_tag_click(event):
mouse_index = self.path_bar.index("@%d,%d" % (event.x, event.y))
lineno = int(float(mouse_index))
if lineno == 1:
self.request_focus_into("")
else:
assert lineno == 2
dir_range = get_dir_range(event)
if dir_range:
_, end_index = dir_range
path = self.path_bar.get("2.0", end_index)
if path.endswith(":"):
path += "\\"
self.request_focus_into(path)
self.path_bar.tag_bind("dir", "<1>", dir_tag_click)
self.path_bar.tag_bind("dir", "<Enter>", dir_tag_enter)
self.path_bar.tag_bind("dir", "<Leave>", dir_tag_leave)
self.path_bar.tag_bind("dir", "<Motion>", dir_tag_motion)
# self.menu_button = ttk.Button(header_frame, text="≡ ", style="ViewToolbar.Toolbutton")
self.menu_button = CustomToolbutton(
header_frame,
style="ViewToolbar.Toolbutton",
text=f" {get_menu_char()} ",
command=self.post_button_menu,
)
# self.menu_button.grid(row=0, column=1, sticky="ne")
self.menu_button.place(anchor="ne", rely=0, relx=1)
def clear(self):
self.clear_error()
self.invalidate_cache()
self.path_bar.direct_delete("1.0", "end")
self.tree.set_children("")
self.current_focus = None
def path_exists(self, path: str) -> Optional[bool]:
return None
def request_focus_into(self, path):
return self.focus_into(path)
def focus_into(self, path):
logger.info("focus_into %r", path)
self.clear_error()
self.invalidate_cache()
# clear
self.tree.set_children(ROOT_NODE_ID)
self.tree.set(ROOT_NODE_ID, "path", path)
self.building_breadcrumbs = True
self.path_bar.direct_delete("1.0", "end")
self.path_bar.direct_insert("1.0", self.get_root_text(), ("dir",))
if path and path != "/":
self.path_bar.direct_insert("end", "\n")
def create_spacer():
return ttk.Frame(self.path_bar, height=1, width=4, style="ViewToolbar.TFrame")
parts = self.split_path(path)
for i, part in enumerate(parts):
if i > 0:
if parts[i - 1] != "":
self.path_bar.window_create("end", window=create_spacer())
self.path_bar.direct_insert("end", self.get_dir_separator())
self.path_bar.window_create("end", window=create_spacer())
tags = ("dir",)
partial_path = self.path_bar.get("2.0", "end").strip() + part
if self.is_project_dir(partial_path):
tags += ("project",)
elif self.is_venv_dir(partial_path):
tags += ("venv",)
self.path_bar.direct_insert("end", part, tags=tags)
self.building_breadcrumbs = False
self.resize_path_bar()
self.render_children_from_cache()
self.scroll_to_top()
self.current_focus = path
def scroll_to_top(self):
children = self.tree.get_children()
if children:
self.tree.see(children[0])
def split_path(self, path):
return path.split(self.get_dir_separator())
def get_root_text(self):
return get_local_files_root_text()
def on_open_node(self, event):
node_id = self.get_selected_node()
if self.get_selected_kind() == "file":
# can happen in Windows when pressing ENTER on file
return "break"
path = self.tree.set(node_id, "path")
if path: # and path not in self._cached_child_data:
self.render_children_from_cache(node_id)
# self.request_dirs_child_data(node_id, [path])
# else:
def resize_path_bar(self, event=None):
if self.building_breadcrumbs:
return
height = self.tk.call((self.path_bar, "count", "-update", "-displaylines", "1.0", "end"))
self.path_bar.configure(height=height)
def _cleaned_selection(self):
# In some cases (eg. Python 3.6.9 and Tk 8.6.8 in Ubuntu when selecting a range with shift),
# nodes may contain collapsed children.
# In most cases this does no harm, because the command would apply to children as well,
# but dummy dir marker nodes may cause confusion
nodes = self.tree.selection()
return [node for node in nodes if self.tree.item(node, "text") != _dummy_node_text]
def get_selected_node(self):
"""Returns single node (or nothing)"""
nodes = self._cleaned_selection()
if len(nodes) == 1:
return nodes[0]
elif len(nodes) > 1:
return self.tree.focus() or None
else:
return None
def get_selected_nodes(self, notify_if_empty=False):
"""Can return several nodes"""
result = self._cleaned_selection()
if not result and notify_if_empty:
self.notify_missing_selection()
return result
def get_selection_info(self, notify_if_empty=False):
nodes = self.get_selected_nodes(notify_if_empty)
if not nodes:
return None
elif len(nodes) == 1:
description = "'" + self.tree.set(nodes[0], "name") + "'"
else:
description = tr("%d items") % len(nodes)
paths = [self.tree.set(node, "path") for node in nodes]
kinds = [self.tree.set(node, "kind") for node in nodes]
return {"description": description, "nodes": nodes, "paths": paths, "kinds": kinds}
def get_selected_path(self):
return self.get_selected_value("path")
def get_selected_kind(self):
return self.get_selected_value("kind")
def get_selected_name(self):
return self.get_selected_value("name")
def get_extension_from_name(self, name):
if name is None:
return None
if "." in name:
return "." + name.split(".")[-1].lower()
else:
return name.lower()
def get_selected_value(self, key):
node_id = self.get_selected_node()
if node_id:
return self.tree.set(node_id, key)
else:
return None
def get_active_directory(self):
path = self.tree.set(ROOT_NODE_ID, "path")
return path
def request_dirs_child_data(self, node_id, paths):
raise NotImplementedError()
def show_fs_info(self):
path = self.get_selected_path()
if path is None:
path = self.current_focus
self.request_fs_info(path)
def request_fs_info(self, path):
raise NotImplementedError()
def present_fs_info(self, info):
total_str = "?" if info["total"] is None else sizeof_fmt(info["total"])
used_str = "?" if info["used"] is None else sizeof_fmt(info["used"])
free_str = "?" if info["free"] is None else sizeof_fmt(info["free"])
text = tr("Storage space on this drive or filesystem") + ":\n\n" " %s: %s\n" % (
tr("total space"),
total_str,
) + " %s: %s\n" % (tr("used space"), used_str) + " %s: %s\n" % (
tr("free space"),
free_str,
)
if info.get("comment"):
text += "\n" + info["comment"]
messagebox.showinfo(tr("Storage info"), text, master=self)
def cache_dirs_child_data(self, data):
from copy import deepcopy
data = deepcopy(data)
for parent_path in data:
children_data = data[parent_path]
if isinstance(children_data, dict):
for child_name in children_data:
child_data = children_data[child_name]
assert isinstance(child_data, dict)
if "label" not in child_data:
child_data["label"] = child_name
if "isdir" not in child_data:
child_data["isdir"] = child_data.get("size_bytes", 0) is None
else:
assert children_data is None
self._cached_child_data.update(data)
def file_exists_in_cache(self, path):
for parent_path in self._cached_child_data:
# hard to split because it may not be in this system format
name = path[len(parent_path) :]
if name[0:1] in ["/", "\\"]:
name = name[1:]
if name in self._cached_child_data[parent_path]:
return True
return False
def select_path_if_visible(self, path, node_id=""):
for child_id in self.tree.get_children(node_id):
if self.tree.set(child_id, "path") == path:
self.tree.selection_set(child_id)
return
if self._is_open_dir_node(child_id):
self.select_path_if_visible(path, child_id)
def _is_open_dir_node(self, node_id) -> bool:
# In Windows a node may get open=True simply by pressing ENTER on it
return self.tree.item(node_id, "open") and self.tree.set(node_id, "kind") != "file"
def get_open_paths(self, node_id=ROOT_NODE_ID):
if self.tree.set(node_id, "kind") == "file":
return set()
elif node_id == ROOT_NODE_ID or self._is_open_dir_node(node_id):
result = {self.tree.set(node_id, "path")}
for child_id in self.tree.get_children(node_id):
result.update(self.get_open_paths(child_id))
return result
else:
return set()
def invalidate_cache(self, paths=None):
if paths is None:
self._cached_child_data.clear()
else:
for path in paths:
if path in self._cached_child_data:
del self._cached_child_data[path]
def render_children_from_cache(self, node_id=""):
"""This node is supposed to be a directory and
its contents needs to be shown and/or refreshed"""
path = self.tree.set(node_id, "path")
kind = self.tree.set(node_id, "kind")
if kind == "file":
logger.warning("File %r is treated as dir", path)
return
logger.debug("Rendering %r from cache", path)
if path not in self._cached_child_data:
self.request_dirs_child_data(node_id, self.get_open_paths() | {path})
# leave it as is for now, it will be updated later
return
children_data = self._cached_child_data[path]
if children_data in ["file", "missing"]:
# path used to be a dir but is now a file or does not exist
# if browser is focused into this path
if node_id == "":
self.show_error("Directory " + path + " does not exist anymore", node_id)
elif children_data == "missing":
self.tree.delete(node_id)
else:
assert children_data == "file"
self.tree.set_children(node_id) # clear the list of children
self.tree.item(node_id, open=False)
elif children_data is None:
raise RuntimeError("None data for %s" % path)
else:
children_data = {
name: atts
for (name, atts) in children_data.items()
if self.item_matches_filter(name, atts)
}
fs_children_names = children_data.keys()
tree_children_ids = self.tree.get_children(node_id)
# recollect children
children = {}
# first the ones, which are present already in tree
for child_id in tree_children_ids:
name = self.tree.set(child_id, "name")
if name in fs_children_names:
children[name] = child_id
self.update_node_data(child_id, name, children_data[name])
# add missing children
for name in fs_children_names:
if name not in children:
child_path = self.join(path, name)
if self.is_project_dir(child_path):
tags = ("project",)
elif self.is_venv_dir(child_path):
tags = "venv"
else:
tags = ()
child_id = self.tree.insert(node_id, "end", tags=tags)
children[name] = child_id
self.tree.set(children[name], "path", child_path)
self.update_node_data(child_id, name, children_data[name])
def file_order(name):
# items in a folder should be ordered so that
# folders come first and names are ordered case insensitively
if self.order_by == "size":
return (
not children_data[name]["isdir"], # prefer directories
not ":" in name, # prefer drives
children_data[name]["size_bytes"],
name.upper(),
name,
)
elif self.order_by == "modified":
return (
-children_data[name]["modified_epoch"], # prefer newer files
name.upper(),
name,
)
else:
return (
not children_data[name]["isdir"], # prefer directories
not ":" in name, # prefer drives
name.upper(),
name,
)
# update tree
ids_sorted_by_name = list(
map(
lambda key: children[key],
sorted(children.keys(), key=file_order, reverse=self.reverse_order),
)
)
self.tree.set_children(node_id, *ids_sorted_by_name)
# recursively update open children
for child_id in ids_sorted_by_name:
if self._is_open_dir_node(child_id):
self.render_children_from_cache(child_id)
def show_error(self, msg, node_id=""):
if not node_id:
# clear tree
self.tree.set_children("")
err_id = self.tree.insert(node_id, "end")
self.tree.item(err_id, text=msg)
self.tree.set_children(node_id, err_id)
def clear_error(self):
"TODO:"
def update_node_data(self, node_id, name, data):
assert node_id != ""
path = self.tree.set(node_id, "path")
if data.get("modified_epoch"):
try:
# modification time is Unix epoch
time_str = format_date_and_time_compact(
time.localtime(int(data["modified_epoch"])),
without_seconds=True,
optimize_year=True,
)
except Exception:
logger.exception("Could not format modified (%r)", data.get("modified_epoch"))
time_str = ""
else:
time_str = ""
self.tree.set(node_id, "modified_fmt", time_str)
self.tree.set(node_id, "modified_epoch", data.get("modified_epoch", ""))
if data["isdir"]:
self.tree.set(node_id, "kind", "dir")
self.tree.set(node_id, "size_fmt", "")
self.tree.set(node_id, "size_bytes", "")
# Ensure that expand button is visible
# unless we know it doesn't have children
children_ids = self.tree.get_children(node_id)
if (
self.show_expand_buttons
and len(children_ids) == 0
and (path not in self._cached_child_data or self._cached_child_data[path])
):
self.tree.insert(node_id, "end", text=_dummy_node_text)
if path.endswith(":") or path.endswith(":\\"):
img = self.hard_drive_icon
else:
img = self.folder_icon
else:
self.tree.set(node_id, "kind", "file")
self.tree.set(node_id, "size_bytes", data["size_bytes"])
self.tree.set(node_id, "size_fmt", sizeof_fmt(data["size_bytes"]))
# Make sure it doesn't have children
self.tree.set_children(node_id)
if (
path.lower().endswith(".py")
or path.lower().endswith(".pyw")
or path.lower().endswith(".pyi")
or path.lower().endswith(".pyde")
):
img = self.python_file_icon
elif self.should_open_name_in_thonny(name):
img = self.text_file_icon
else:
img = self.generic_file_icon
self.tree.set(node_id, "name", name)
self.tree.item(node_id, text=" " + data["label"], image=img)
def join(self, parent, child):
if parent == "":
if self.get_dir_separator() == "/":
return "/" + child
else:
return child
if parent.endswith(self.get_dir_separator()):
return parent + child
else:
return parent + self.get_dir_separator() + child
def get_dir_separator(self):
return os.path.sep
def on_double_click(self, event):
# TODO: don't act when the click happens below last item
path = self.get_selected_path()
kind = self.get_selected_kind()
name = self.get_selected_name()
if kind == "file":
if self.should_open_name_in_thonny(name):
self.open_file(path)
else:
self.open_path_with_system_app(path)
elif kind == "dir":
self.request_focus_into(path)
return "break"
def open_file(self, path):
pass
def open_path_with_system_app(self, path):
pass
def on_secondary_click(self, event):
node_id = self.tree.identify_row(event.y)
if node_id:
if node_id not in self.tree.selection():
# replace current selection
self.tree.selection_set(node_id)
self.tree.focus(node_id)
else:
self.tree.selection_set()
self.path_bar.focus_set()
self.tree.update()
self.refresh_menu(context="item")
self.menu.tk_popup(event.x_root, event.y_root)
def post_button_menu(self):
self.refresh_menu(context="button")
self.menu.tk_popup(
self.menu_button.winfo_rootx(),
self.menu_button.winfo_rooty() + self.menu_button.winfo_height(),
)
def refresh_menu(self, context):
self.menu.delete(0, "end")
self.add_first_menu_items(context)
self.menu.add_separator()
self.add_middle_menu_items(context)
self.menu.add_separator()
self.add_last_menu_items(context)
def is_active_browser(self):
return False
def add_first_menu_items(self, context):
if context == "item":
selected_path = self.get_selected_path()
selected_kind = self.get_selected_kind()
else:
selected_path = self.get_active_directory()
selected_kind = "dir"
if context == "button":
self.menu.add_command(label=tr("Refresh"), command=self.cmd_refresh_tree)
self.menu.add_command(
label=tr("Open in system file manager"),
command=lambda: self.open_path_with_system_app(selected_path),
)
else:
if selected_kind == "dir":
self.menu.add_command(
label=tr("Focus into"), command=lambda: self.request_focus_into(selected_path)
)
else:
self.menu.add_command(
label=tr("Open in PyStart"), command=lambda: self.open_file(selected_path)
)
if self.is_active_browser():
self.menu.add_command(
label=tr("Open in default external app"),
command=lambda: self.open_path_with_system_app(selected_path),
)
if selected_kind == "file":
ext = self.get_extension_from_name(self.get_selected_name())
self.menu.add_command(
label=tr("Configure %s files") % ext + "...",
command=lambda: self.open_extension_dialog(ext),
)
hidden_files_label = (
tr("Hide hidden files") if show_hidden_files() else tr("Show hidden files")
)
self.menu.add_command(label=hidden_files_label, command=self.toggle_hidden_files)
def toggle_hidden_files(self):
get_workbench().set_option(
HIDDEN_FILES_OPTION, not get_workbench().get_option(HIDDEN_FILES_OPTION)
)
self.refresh_tree()
def cmd_refresh_tree(self):
self.refresh_tree()
def open_extension_dialog(self, extension: str) -> None:
system_choice = tr("Open in system default app")
thonny_choice = tr("Open in PyStart's text editor")
current_index = (
1 if get_workbench().get_option(get_file_handler_conf_key(extension)) == "pystart" else 0
)
choice = ask_one_from_choices(
title=tr("Configure %s files") % extension,
question=tr(
"What to do with a %s file when you double-click it in PyStart's file browser?"
)
% extension,
choices=[system_choice, thonny_choice],
initial_choice_index=current_index,
master=self.winfo_toplevel(),
)
if not choice:
return
get_workbench().set_option(
get_file_handler_conf_key(extension),
"system" if choice == system_choice else "pystart",
)
# update icons
self.refresh_tree()
def add_middle_menu_items(self, context):
if self.supports_new_file():
self.menu.add_command(label=tr("New file") + "...", command=self.create_new_file)
if self.supports_directories():
self.menu.add_command(label=tr("New directory") + "...", command=self.mkdir)
if self.supports_copypaste():
self.menu.add_command(label=tr("Cut"), command=self.cut_files)
self.menu.add_command(label=tr("Copy"), command=self.copy_files)
target = self.get_selected_file()
self.menu.add_command(label=tr("Paste"), command=self.paste_files)
if (
target is None
or not self.copypaste.has_selection()
or self.copypaste.conflicts(target)
):
self.menu.entryconfig(tr("Paste"), state="disabled")
if self.supports_rename():
self.menu.add_command(label=tr("Rename"), command=self.rename_file)
if self.supports_trash():
trash_label = tr("Move to Trash")
self.menu.add_command(label=trash_label, command=self.move_to_trash)
else:
self.menu.add_command(label=tr("Delete"), command=self.delete)
def add_last_menu_items(self, context):
self.menu.add_command(label=tr("Properties"), command=self.show_properties)
if context == "button":
self.menu.add_command(label=tr("Storage space"), command=self.show_fs_info)
def show_properties(self):
node_id = self.get_selected_node()
if node_id is None:
self.notify_missing_selection()
return
values = self.tree.set(node_id)
text = tr("Path") + ":\n " + values["path"] + "\n\n"
if values["kind"] == "dir":
title = tr("Directory properties")
else:
title = tr("File properties")
size_fmt_str = values["size_fmt"]
bytes_str = str(values["size_bytes"]) + " " + tr("bytes")
text += (
tr("Size")
+ ":\n "
+ (
bytes_str
if size_fmt_str.endswith(" B")
else size_fmt_str + " (" + bytes_str + ")"
)
+ "\n\n"
)
if values["modified_fmt"].strip():
text += tr("Modified") + ":\n " + values["modified_fmt"] + "\n\n"
messagebox.showinfo(title, text.strip(), master=self)
def refresh_tree(self, paths_to_invalidate=None):
self.invalidate_cache(paths_to_invalidate)
if self.winfo_ismapped():
self.render_children_from_cache("")
if self.path_to_highlight:
self.select_path_if_visible(self.path_to_highlight)
self.path_to_highlight = None
def create_new_file(self):
selected_node_id = self.get_selected_node()
if selected_node_id:
selected_path = self.tree.set(selected_node_id, "path")
selected_kind = self.tree.set(selected_node_id, "kind")
if selected_kind == "dir":
parent_path = selected_path
else:
parent_id = self.tree.parent(selected_node_id)
parent_path = self.tree.set(parent_id, "path")
else:
parent_path = self.current_focus
name = ask_string(
"File name", "Provide filename", initial_value="", master=self.winfo_toplevel()
)
if not name:
return None
path = self.join(parent_path, name)
if self.path_exists(path):
messagebox.showerror("Error", "The file '" + path + "' already exists", master=self)
return self.create_new_file()
else:
self.create_new_file_editor(path)
return path
def create_new_file_editor(self, path):
raise NotImplementedError()
def delete(self):
selection = self.get_selection_info(True)
if not selection:
return
confirmation = "Are you sure want to delete %s?" % selection["description"]
confirmation += "\n\nNB! Trash bin won't be used (no way to undelete)!"
if "dir" in selection["kinds"]:
confirmation += "\n" + "Directories will be deleted with content."
if not messagebox.askyesno("Are you sure?", confirmation, master=self):
return
self.perform_delete(selection["paths"], tr("Deleting %s") % selection["description"])
self.refresh_tree()
def move_to_trash(self):
assert self.supports_trash()
selection = self.get_selection_info(True)
if not selection:
return
if not messagebox.askokcancel(
tr("Moving to Trash"),
tr("Move %s to Trash?") % selection["description"],
icon="info",
master=self,
):
return
self.perform_move_to_trash(
selection["paths"], tr("Moving %s to Trash") % (selection["description"])
)
self.refresh_tree()
def supports_trash(self):
return False
def mkdir(self):
parent = self.get_selected_path()
if parent is None:
parent = self.current_focus
else:
if self.get_selected_kind() == "file":
# dirname does the right thing even if parent is Linux path and running on Windows
parent = os.path.dirname(parent)
name = ask_string(
tr("New directory"),
tr("Enter name for new directory under\n%s") % parent,
master=self.winfo_toplevel(),
)
if not name or not name.strip():
return
self.perform_mkdir(parent, name.strip())
self.refresh_tree()
def perform_delete(self, paths, description):
raise NotImplementedError()
def perform_move_to_trash(self, paths, description):
raise NotImplementedError()
def supports_directories(self):
return True
def perform_mkdir(self, parent_dir, name):
raise NotImplementedError()
def notify_missing_selection(self):
messagebox.showerror(
tr("Nothing selected"), tr("Select an item and try again!"), master=self
)
def should_open_name_in_thonny(self, name):
ext = self.get_extension_from_name(name)
return get_workbench().get_option(get_file_handler_conf_key(ext), "system") == "pystart"
def supports_new_file(self):
return False
def get_selected_file(self):
selection = self.get_selection_info(False)
if not selection or len(selection["paths"]) > 1:
return