forked from jblindsay/whitebox-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wb_runner.py
1327 lines (1157 loc) · 57 KB
/
wb_runner.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
#!/usr/bin/env python3
# This script is part of the WhiteboxTools geospatial analysis library.
# Authors: Dr. John Lindsay, Rachel Broders
# Created: 28/11/2017
# Last Modified: 05/11/2019
# License: MIT
import __future__
import sys
# if sys.version_info[0] < 3:
# raise Exception("Must be using Python 3")
import json
import os
from os import path
# from __future__ import print_function
# from enum import Enum
import platform
import re #Added by Rachel for snake_to_camel function
from pathlib import Path
import glob
from sys import platform as _platform
import shlex
import tkinter as tk
from tkinter import ttk
from tkinter.scrolledtext import ScrolledText
from tkinter import filedialog
from tkinter import messagebox
from tkinter import PhotoImage
import webbrowser
from whitebox_tools import WhiteboxTools, to_camelcase
wbt = WhiteboxTools()
class FileSelector(tk.Frame):
def __init__(self, json_str, runner, master=None):
# first make sure that the json data has the correct fields
j = json.loads(json_str)
self.name = j['name']
self.description = j['description']
self.flag = j['flags'][len(j['flags']) - 1]
self.parameter_type = j['parameter_type']
self.file_type = ""
if "ExistingFile" in self.parameter_type:
self.file_type = j['parameter_type']['ExistingFile']
elif "NewFile" in self.parameter_type:
self.file_type = j['parameter_type']['NewFile']
self.optional = j['optional']
default_value = j['default_value']
self.runner = runner
ttk.Frame.__init__(self, master, padding='0.02i')
self.grid()
self.label = ttk.Label(self, text=self.name, justify=tk.LEFT)
self.label.grid(row=0, column=0, sticky=tk.W)
self.label.columnconfigure(0, weight=1)
if not self.optional:
self.label['text'] = self.label['text'] + "*"
fs_frame = ttk.Frame(self, padding='0.0i')
self.value = tk.StringVar()
self.entry = ttk.Entry(
fs_frame, width=45, justify=tk.LEFT, textvariable=self.value)
self.entry.grid(row=0, column=0, sticky=tk.NSEW)
self.entry.columnconfigure(0, weight=1)
if default_value:
self.value.set(default_value)
# dir_path = os.path.dirname(os.path.realpath(__file__))
# print(dir_path)
# self.open_file_icon = tk.PhotoImage(file = dir_path + '//img//open.png') #Added by Rachel to replace file selector "..." button with open file icon
# self.open_button = ttk.Button(fs_frame, width=4, image = self.open_file_icon, command=self.select_file, padding = '0.02i')
self.open_button = ttk.Button(fs_frame, width=4, text="...", command=self.select_file, padding = '0.02i')
self.open_button.grid(row=0, column=1, sticky=tk.E)
self.open_button.columnconfigure(0, weight=1)
fs_frame.grid(row=1, column=0, sticky=tk.NSEW)
fs_frame.columnconfigure(0, weight=10)
fs_frame.columnconfigure(1, weight=1)
# self.pack(fill=tk.BOTH, expand=1)
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
self.rowconfigure(1, weight=1)
# Add the bindings
if _platform == "darwin":
self.entry.bind("<Command-Key-a>", self.select_all)
else:
self.entry.bind("<Control-Key-a>", self.select_all)
def select_file(self):
try:
result = self.value.get()
if self.parameter_type == "Directory":
result = filedialog.askdirectory(initialdir=self.runner.working_dir, title="Select directory")
elif "ExistingFile" in self.parameter_type:
ftypes = [('All files', '*.*')]
if 'RasterAndVector' in self.file_type:
ftypes = [("Shapefiles", "*.shp"), ('Raster files', ('*.dep', '*.tif',
'*.tiff', '*.bil', '*.flt',
'*.sdat', '*.rdc',
'*.asc'))]
elif 'Raster' in self.file_type:
ftypes = [('Raster files', ('*.dep', '*.tif',
'*.tiff', '*.bil', '*.flt',
'*.sdat', '*.rdc',
'*.asc'))]
elif 'Lidar' in self.file_type:
ftypes = [("LiDAR files", ('*.las', '*.zlidar', '*.zip'))]
elif 'Vector' in self.file_type:
ftypes = [("Shapefiles", "*.shp")]
elif 'Text' in self.file_type:
ftypes = [("Text files", "*.txt"), ("all files", "*.*")]
elif 'Csv' in self.file_type:
ftypes = [("CSC files", "*.csv"), ("all files", "*.*")]
elif 'Html' in self.file_type:
ftypes = [("HTML files", "*.html")]
result = filedialog.askopenfilename(
initialdir=self.runner.working_dir, title="Select file", filetypes=ftypes)
elif "NewFile" in self.parameter_type:
result = filedialog.asksaveasfilename()
self.value.set(result)
# update the working directory
self.runner.working_dir = os.path.dirname(result)
except:
t = "file"
if self.parameter_type == "Directory":
t = "directory"
messagebox.showinfo("Warning", "Could not find {}".format(t))
def get_value(self):
if self.value.get():
v = self.value.get()
# Do some quality assurance here.
# Is there a directory included?
if not path.dirname(v):
v = path.join(self.runner.working_dir, v)
# What about a file extension?
ext = os.path.splitext(v)[-1].lower().strip()
if not ext:
ext = ""
if 'RasterAndVector' in self.file_type:
ext = '.tif'
elif 'Raster' in self.file_type:
ext = '.tif'
elif 'Lidar' in self.file_type:
ext = '.las'
elif 'Vector' in self.file_type:
ext = '.shp'
elif 'Text' in self.file_type:
ext = '.txt'
elif 'Csv' in self.file_type:
ext = '.csv'
elif 'Html' in self.file_type:
ext = '.html'
v += ext
v = path.normpath(v)
return "{}='{}'".format(self.flag, v)
else:
t = "file"
if self.parameter_type == "Directory":
t = "directory"
if not self.optional:
messagebox.showinfo(
"Error", "Unspecified {} parameter {}.".format(t, self.flag))
return None
def select_all(self, event):
self.entry.select_range(0, tk.END)
return 'break'
class FileOrFloat(tk.Frame):
def __init__(self, json_str, runner, master=None):
# first make sure that the json data has the correct fields
j = json.loads(json_str)
self.name = j['name']
self.description = j['description']
self.flag = j['flags'][len(j['flags']) - 1]
self.parameter_type = j['parameter_type']
self.file_type = j['parameter_type']['ExistingFileOrFloat']
self.optional = j['optional']
default_value = j['default_value']
self.runner = runner
ttk.Frame.__init__(self, master)
self.grid()
self['padding'] = '0.02i'
self.label = ttk.Label(self, text=self.name, justify=tk.LEFT)
self.label.grid(row=0, column=0, sticky=tk.W)
self.label.columnconfigure(0, weight=1)
if not self.optional:
self.label['text'] = self.label['text'] + "*"
fs_frame = ttk.Frame(self, padding='0.0i')
self.value = tk.StringVar()
self.entry = ttk.Entry(
fs_frame, width=35, justify=tk.LEFT, textvariable=self.value)
self.entry.grid(row=0, column=0, sticky=tk.NSEW)
self.entry.columnconfigure(0, weight=1)
if default_value:
self.value.set(default_value)
# self.img = tk.PhotoImage(file=script_dir + "/img/open.gif")
# self.open_button = ttk.Button(fs_frame, width=55, image=self.img, command=self.select_dir)
self.open_button = ttk.Button(
fs_frame, width=4, text="...", command=self.select_file)
self.open_button.grid(row=0, column=1, sticky=tk.E)
# self.open_button.columnconfigure(0, weight=1)
self.label = ttk.Label(fs_frame, text='OR', justify=tk.LEFT)
self.label.grid(row=0, column=2, sticky=tk.W)
# self.label.columnconfigure(0, weight=1)
self.value2 = tk.StringVar()
self.entry2 = ttk.Entry(
fs_frame, width=10, justify=tk.LEFT, textvariable=self.value2)
self.entry2.grid(row=0, column=3, sticky=tk.NSEW)
self.entry2.columnconfigure(0, weight=1)
self.entry2['justify'] = 'right'
fs_frame.grid(row=1, column=0, sticky=tk.NSEW)
fs_frame.columnconfigure(0, weight=10)
fs_frame.columnconfigure(1, weight=1)
# self.pack(fill=tk.BOTH, expand=1)
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
self.rowconfigure(1, weight=1)
# Add the bindings
if _platform == "darwin":
self.entry.bind("<Command-Key-a>", self.select_all)
else:
self.entry.bind("<Control-Key-a>", self.select_all)
def select_file(self):
try:
result = self.value.get()
ftypes = [('All files', '*.*')]
if 'RasterAndVector' in self.file_type:
ftypes = [("Shapefiles", "*.shp"), ('Raster files', ('*.dep', '*.tif',
'*.tiff', '*.bil', '*.flt',
'*.sdat', '*.rdc',
'*.asc'))]
elif 'Raster' in self.file_type:
ftypes = [('Raster files', ('*.dep', '*.tif',
'*.tiff', '*.bil', '*.flt',
'*.sdat', '*.rdc',
'*.asc'))]
elif 'Lidar' in self.file_type:
ftypes = [("LiDAR files", ('*.las', '*.zlidar', '*.zip'))]
elif 'Vector' in self.file_type:
ftypes = [("Shapefiles", "*.shp")]
elif 'Text' in self.file_type:
ftypes = [("Text files", "*.txt"), ("all files", "*.*")]
elif 'Csv' in self.file_type:
ftypes = [("CSC files", "*.csv"), ("all files", "*.*")]
elif 'Html' in self.file_type:
ftypes = [("HTML files", "*.html")]
result = filedialog.askopenfilename(
initialdir=self.runner.working_dir, title="Select file", filetypes=ftypes)
self.value.set(result)
# update the working directory
self.runner.working_dir = os.path.dirname(result)
except:
t = "file"
if self.parameter_type == "Directory":
t = "directory"
messagebox.showinfo("Warning", "Could not find {}".format(t))
def RepresentsFloat(self, s):
try:
float(s)
return True
except ValueError:
return False
def get_value(self):
if self.value.get():
v = self.value.get()
# Do some quality assurance here.
# Is there a directory included?
if not path.dirname(v):
v = path.join(self.runner.working_dir, v)
# What about a file extension?
ext = os.path.splitext(v)[-1].lower()
if not ext:
ext = ""
if 'RasterAndVector' in self.file_type:
ext = '.tif'
elif 'Raster' in self.file_type:
ext = '.tif'
elif 'Lidar' in self.file_type:
ext = '.las'
elif 'Vector' in self.file_type:
ext = '.shp'
elif 'Text' in self.file_type:
ext = '.txt'
elif 'Csv' in self.file_type:
ext = '.csv'
elif 'Html' in self.file_type:
ext = '.html'
v = v + ext
v = path.normpath(v)
return "{}='{}'".format(self.flag, v)
elif self.value2.get():
v = self.value2.get()
if self.RepresentsFloat(v):
return "{}={}".format(self.flag, v)
else:
messagebox.showinfo(
"Error", "Error converting parameter {} to type Float.".format(self.flag))
else:
if not self.optional:
messagebox.showinfo(
"Error", "Unspecified file/numeric parameter {}.".format(self.flag))
return None
def select_all(self, event):
self.entry.select_range(0, tk.END)
return 'break'
class MultifileSelector(tk.Frame):
def __init__(self, json_str, runner, master=None):
# first make sure that the json data has the correct fields
j = json.loads(json_str)
self.name = j['name']
self.description = j['description']
self.flag = j['flags'][len(j['flags']) - 1]
self.parameter_type = j['parameter_type']
self.file_type = ""
self.file_type = j['parameter_type']['FileList']
self.optional = j['optional']
default_value = j['default_value']
self.runner = runner
ttk.Frame.__init__(self, master)
self.grid()
self['padding'] = '0.05i'
self.label = ttk.Label(self, text=self.name, justify=tk.LEFT)
self.label.grid(row=0, column=0, sticky=tk.W)
self.label.columnconfigure(0, weight=1)
if not self.optional:
self.label['text'] = self.label['text'] + "*"
fs_frame = ttk.Frame(self, padding='0.0i')
# , variable=self.value)
self.opt = tk.Listbox(fs_frame, width=44, height=4)
self.opt.grid(row=0, column=0, sticky=tk.NSEW)
s = ttk.Scrollbar(fs_frame, orient=tk.VERTICAL, command=self.opt.yview)
s.grid(row=0, column=1, sticky=(tk.N, tk.S))
self.opt['yscrollcommand'] = s.set
btn_frame = ttk.Frame(fs_frame, padding='0.0i')
self.open_button = ttk.Button(
btn_frame, width=4, text="...", command=self.select_file)
self.open_button.grid(row=0, column=0, sticky=tk.NE)
self.open_button.columnconfigure(0, weight=1)
self.open_button.rowconfigure(0, weight=1)
self.delete_button = ttk.Button(
btn_frame, width=4, text="del", command=self.delete_entry)
self.delete_button.grid(row=1, column=0, sticky=tk.NE)
self.delete_button.columnconfigure(0, weight=1)
self.delete_button.rowconfigure(1, weight=1)
btn_frame.grid(row=0, column=2, sticky=tk.NE)
fs_frame.grid(row=1, column=0, sticky=tk.NSEW)
fs_frame.columnconfigure(0, weight=10)
fs_frame.columnconfigure(1, weight=1)
fs_frame.columnconfigure(2, weight=1)
# self.pack(fill=tk.BOTH, expand=1)
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
self.rowconfigure(1, weight=1)
def select_file(self):
try:
#result = self.value.get()
init_dir = self.runner.working_dir
ftypes = [('All files', '*.*')]
if 'RasterAndVector' in self.file_type:
ftypes = [("Shapefiles", "*.shp"), ('Raster files', ('*.dep', '*.tif',
'*.tiff', '*.bil', '*.flt',
'*.sdat', '*.rdc',
'*.asc'))]
elif 'Raster' in self.file_type:
ftypes = [('Raster files', ('*.dep', '*.tif',
'*.tiff', '*.bil', '*.flt',
'*.sdat', '*.rdc',
'*.asc'))]
elif 'Lidar' in self.file_type:
ftypes = [("LiDAR files", ('*.las', '*.zlidar', '*.zip'))]
elif 'Vector' in self.file_type:
ftypes = [("Shapefiles", "*.shp")]
elif 'Text' in self.file_type:
ftypes = [("Text files", "*.txt"), ("all files", "*.*")]
elif 'Csv' in self.file_type:
ftypes = [("CSC files", "*.csv"), ("all files", "*.*")]
elif 'Html' in self.file_type:
ftypes = [("HTML files", "*.html")]
result = filedialog.askopenfilenames(
initialdir=init_dir, title="Select files", filetypes=ftypes)
if result:
for v in result:
self.opt.insert(tk.END, v)
# update the working directory
self.runner.working_dir = os.path.dirname(result[0])
except:
messagebox.showinfo("Warning", "Could not find file")
def delete_entry(self):
self.opt.delete(tk.ANCHOR)
def get_value(self):
try:
l = self.opt.get(0, tk.END)
if l:
s = ""
for i in range(0, len(l)):
v = l[i]
if not path.dirname(v):
v = path.join(self.runner.working_dir, v)
v = path.normpath(v)
if i < len(l) - 1:
s += "{};".format(v)
else:
s += "{}".format(v)
return "{}='{}'".format(self.flag, s)
else:
if not self.optional:
messagebox.showinfo(
"Error", "Unspecified non-optional parameter {}.".format(self.flag))
except:
messagebox.showinfo(
"Error", "Error formating files for parameter {}".format(self.flag))
return None
class BooleanInput(tk.Frame):
def __init__(self, json_str, master=None):
# first make sure that the json data has the correct fields
j = json.loads(json_str)
self.name = j['name']
self.description = j['description']
self.flag = j['flags'][len(j['flags']) - 1]
self.parameter_type = j['parameter_type']
# just for quality control. BooleanInputs are always optional.
self.optional = True
default_value = j['default_value']
ttk.Frame.__init__(self, master)
self.grid()
self['padding'] = '0.05i'
frame = ttk.Frame(self, padding='0.0i')
self.value = tk.IntVar()
c = ttk.Checkbutton(frame, text=self.name,
width=55, variable=self.value)
c.grid(row=0, column=0, sticky=tk.W)
# set the default value
if j['default_value'] != None and j['default_value'] != 'false':
self.value.set(1)
else:
self.value.set(0)
frame.grid(row=1, column=0, sticky=tk.W)
frame.columnconfigure(0, weight=1)
# self.pack(fill=tk.BOTH, expand=1)
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
def get_value(self):
if self.value.get() == 1:
return self.flag
else:
return None
class OptionsInput(tk.Frame):
def __init__(self, json_str, master=None):
# first make sure that the json data has the correct fields
j = json.loads(json_str)
self.name = j['name']
self.description = j['description']
self.flag = j['flags'][len(j['flags']) - 1]
self.parameter_type = j['parameter_type']
self.optional = j['optional']
default_value = j['default_value']
ttk.Frame.__init__(self, master)
self.grid()
self['padding'] = '0.02i'
frame = ttk.Frame(self, padding='0.0i')
self.label = ttk.Label(self, text=self.name, justify=tk.LEFT)
self.label.grid(row=0, column=0, sticky=tk.W)
self.label.columnconfigure(0, weight=1)
frame2 = ttk.Frame(frame, padding='0.0i')
opt = ttk.Combobox(frame2, width=40)
opt.grid(row=0, column=0, sticky=tk.NSEW)
self.value = None # initialize in event of no default and no selection
i = 1
default_index = -1
list = j['parameter_type']['OptionList']
values = ()
for v in list:
values += (v,)
# opt.insert(tk.END, v)
if v == default_value:
default_index = i - 1
i = i + 1
opt['values'] = values
# opt.bind("<<ComboboxSelect>>", self.select)
opt.bind("<<ComboboxSelected>>", self.select)
if default_index >= 0:
opt.current(default_index)
opt.event_generate("<<ComboboxSelected>>")
# opt.see(default_index)
frame2.grid(row=0, column=0, sticky=tk.W)
frame.grid(row=1, column=0, sticky=tk.W)
frame.columnconfigure(0, weight=1)
# self.pack(fill=tk.BOTH, expand=1)
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
# # first make sure that the json data has the correct fields
# j = json.loads(json_str)
# self.name = j['name']
# self.description = j['description']
# self.flag = j['flags'][len(j['flags']) - 1]
# self.parameter_type = j['parameter_type']
# self.optional = j['optional']
# default_value = j['default_value']
# ttk.Frame.__init__(self, master)
# self.grid()
# self['padding'] = '0.1i'
# frame = ttk.Frame(self, padding='0.0i')
# self.label = ttk.Label(self, text=self.name, justify=tk.LEFT)
# self.label.grid(row=0, column=0, sticky=tk.W)
# self.label.columnconfigure(0, weight=1)
# frame2 = ttk.Frame(frame, padding='0.0i')
# opt = tk.Listbox(frame2, width=40) # , variable=self.value)
# opt.grid(row=0, column=0, sticky=tk.NSEW)
# s = ttk.Scrollbar(frame2, orient=tk.VERTICAL, command=opt.yview)
# s.grid(row=0, column=1, sticky=(tk.N, tk.S))
# opt['yscrollcommand'] = s.set
# self.value = None # initialize in event of no default and no selection
# i = 1
# default_index = -1
# list = j['parameter_type']['OptionList']
# for v in list:
# #opt.insert(i, v)
# opt.insert(tk.END, v)
# if v == default_value:
# default_index = i - 1
# i = i + 1
# if i - 1 < 4:
# opt['height'] = i - 1
# else:
# opt['height'] = 3
# opt.bind("<<ListboxSelect>>", self.select)
# if default_index >= 0:
# opt.select_set(default_index)
# opt.event_generate("<<ListboxSelect>>")
# opt.see(default_index)
# frame2.grid(row=0, column=0, sticky=tk.W)
# frame.grid(row=1, column=0, sticky=tk.W)
# frame.columnconfigure(0, weight=1)
# # self.pack(fill=tk.BOTH, expand=1)
# self.columnconfigure(0, weight=1)
# self.rowconfigure(0, weight=1)
def get_value(self):
if self.value:
return "{}='{}'".format(self.flag, self.value)
else:
if not self.optional:
messagebox.showinfo(
"Error", "Unspecified non-optional parameter {}.".format(self.flag))
return None
def select(self, event):
widget = event.widget
# selection = widget.curselection()
self.value = widget.get() # selection[0])
class DataInput(tk.Frame):
def __init__(self, json_str, master=None):
# first make sure that the json data has the correct fields
j = json.loads(json_str)
self.name = j['name']
self.description = j['description']
self.flag = j['flags'][len(j['flags']) - 1]
self.parameter_type = j['parameter_type']
self.optional = j['optional']
default_value = j['default_value']
ttk.Frame.__init__(self, master)
self.grid()
self['padding'] = '0.1i'
self.label = ttk.Label(self, text=self.name, justify=tk.LEFT)
self.label.grid(row=0, column=0, sticky=tk.W)
self.label.columnconfigure(0, weight=1)
self.value = tk.StringVar()
if default_value:
self.value.set(default_value)
else:
self.value.set("")
self.entry = ttk.Entry(self, justify=tk.LEFT, textvariable=self.value)
self.entry.grid(row=0, column=1, sticky=tk.NSEW)
self.entry.columnconfigure(1, weight=10)
if not self.optional:
self.label['text'] = self.label['text'] + "*"
if ("Integer" in self.parameter_type or
"Float" in self.parameter_type or
"Double" in self.parameter_type):
self.entry['justify'] = 'right'
# Add the bindings
if _platform == "darwin":
self.entry.bind("<Command-Key-a>", self.select_all)
else:
self.entry.bind("<Control-Key-a>", self.select_all)
# self.pack(fill=tk.BOTH, expand=1)
self.columnconfigure(0, weight=1)
self.columnconfigure(1, weight=10)
self.rowconfigure(0, weight=1)
def RepresentsInt(self, s):
try:
int(s)
return True
except ValueError:
return False
def RepresentsFloat(self, s):
try:
float(s)
return True
except ValueError:
return False
def get_value(self):
v = self.value.get()
if v:
if "Integer" in self.parameter_type:
if self.RepresentsInt(self.value.get()):
return "{}={}".format(self.flag, self.value.get())
else:
messagebox.showinfo(
"Error", "Error converting parameter {} to type Integer.".format(self.flag))
elif "Float" in self.parameter_type:
if self.RepresentsFloat(self.value.get()):
return "{}={}".format(self.flag, self.value.get())
else:
messagebox.showinfo(
"Error", "Error converting parameter {} to type Float.".format(self.flag))
elif "Double" in self.parameter_type:
if self.RepresentsFloat(self.value.get()):
return "{}={}".format(self.flag, self.value.get())
else:
messagebox.showinfo(
"Error", "Error converting parameter {} to type Double.".format(self.flag))
else: # String or StringOrNumber types
return "{}='{}'".format(self.flag, self.value.get())
else:
if not self.optional:
messagebox.showinfo(
"Error", "Unspecified non-optional parameter {}.".format(self.flag))
return None
def select_all(self, event):
self.entry.select_range(0, tk.END)
return 'break'
class WbRunner(tk.Frame):
def __init__(self, tool_name=None, master=None):
if platform.system() == 'Windows':
self.ext = '.exe'
else:
self.ext = ''
exe_name = "whitebox_tools{}".format(self.ext)
self.exe_path = path.dirname(path.abspath(__file__))
os.chdir(self.exe_path)
for filename in glob.iglob('**/*', recursive=True):
if filename.endswith(exe_name):
self.exe_path = path.dirname(path.abspath(filename))
break
wbt.set_whitebox_dir(self.exe_path)
ttk.Frame.__init__(self, master)
self.script_dir = os.path.dirname(os.path.realpath(__file__))
self.grid()
self.tool_name = tool_name
self.master.title("WhiteboxTools Runner")
if _platform == "darwin":
os.system(
'''/usr/bin/osascript -e 'tell app "Finder" to set frontmost of process "Python" to true' ''')
self.create_widgets()
self.working_dir = str(Path.home())
def create_widgets(self):
#########################################################
# Overall/Top level Frame #
#########################################################
#define left-side frame (toplevel_frame) and right-side frame (overall_frame)
toplevel_frame = ttk.Frame(self, padding='0.1i')
overall_frame = ttk.Frame(self, padding='0.1i')
#set-up layout
overall_frame.grid(row=0, column=1, sticky=tk.NSEW)
toplevel_frame.grid(row=0, column=0, sticky=tk.NSEW)
#########################################################
# Calling basics #
#########################################################
#Create all needed lists of tools and toolboxes
self.toolbox_list = self.get_toolboxes()
self.sort_toolboxes()
self.tools_and_toolboxes = wbt.toolbox('')
self.sort_tools_by_toolbox()
self.get_tools_list()
#Icons to be used in tool treeview
self.tool_icon = tk.PhotoImage(file = self.script_dir + '//img//tool.gif')
self.open_toolbox_icon = tk.PhotoImage(file = self.script_dir + '//img//open.gif')
self.closed_toolbox_icon = tk.PhotoImage(file = self.script_dir + '//img//closed.gif')
#########################################################
# Toolboxes Frame # FIXME: change width or make horizontally scrollable
#########################################################
#define tools_frame and tool_tree
self.tools_frame = ttk.LabelFrame(toplevel_frame, text="{} Available Tools".format(len(self.tools_list)), padding='0.1i')
self.tool_tree = ttk.Treeview(self.tools_frame, height = 21)
#Set up layout
self.tool_tree.grid(row=0, column=0, sticky=tk.NSEW)
self.tool_tree.column("#0", width = 280) #Set width so all tools are readable within the frame
self.tools_frame.grid(row=0, column=0, sticky=tk.NSEW)
self.tools_frame.columnconfigure(0, weight=10)
self.tools_frame.columnconfigure(1, weight=1)
self.tools_frame.rowconfigure(0, weight=10)
self.tools_frame.rowconfigure(1, weight=1)
#Add toolboxes and tools to treeview
index = 0
for toolbox in self.lower_toolboxes:
if toolbox.find('/') != (-1): #toolboxes
self.tool_tree.insert(toolbox[:toolbox.find('/')], 0, text = " " + toolbox[toolbox.find('/') + 1:], iid = toolbox[toolbox.find('/') + 1:], tags = 'toolbox', image = self.closed_toolbox_icon)
for tool in self.sorted_tools[index]: #add tools within toolbox
self.tool_tree.insert(toolbox[toolbox.find('/') + 1:], 'end', text = " " + tool, tags = 'tool', iid = tool, image = self.tool_icon)
else: #subtoolboxes
self.tool_tree.insert('', 'end', text = " " + toolbox, iid = toolbox, tags = 'toolbox', image = self.closed_toolbox_icon)
for tool in self.sorted_tools[index]: #add tools within subtoolbox
self.tool_tree.insert(toolbox, 'end', text = " " + tool, iid = tool, tags = 'tool', image = self.tool_icon)
index = index + 1
#bind tools in treeview to self.tree_update_tool_help function and toolboxes to self.update_toolbox_icon function
self.tool_tree.tag_bind('tool', "<<TreeviewSelect>>", self.tree_update_tool_help)
self.tool_tree.tag_bind('toolbox', "<<TreeviewSelect>>", self.update_toolbox_icon)
#Add vertical scrollbar to treeview frame
s = ttk.Scrollbar(self.tools_frame, orient=tk.VERTICAL,command=self.tool_tree.yview)
s.grid(row=0, column=1, sticky=(tk.N, tk.S))
self.tool_tree['yscrollcommand'] = s.set
#########################################################
# Search Bar #
#########################################################
#create variables for search results and search input
self.search_list = []
self.search_text = tk.StringVar()
#Create the elements of the search frame
self.search_frame = ttk.LabelFrame(toplevel_frame, padding='0.1i', text="{} Tools Found".format(len(self.search_list)))
self.search_label = ttk.Label(self.search_frame, text = "Search: ")
self.search_bar = ttk.Entry(self.search_frame, width = 30, textvariable = self.search_text)
self.search_results_listbox = tk.Listbox(self.search_frame, height=11)
self.search_scroll = ttk.Scrollbar(self.search_frame, orient=tk.VERTICAL, command=self.search_results_listbox.yview)
self.search_results_listbox['yscrollcommand'] = self.search_scroll.set
#Add bindings
self.search_results_listbox.bind("<<ListboxSelect>>", self.search_update_tool_help)
self.search_bar.bind('<Return>', self.update_search)
#Define layout of the frame
self.search_frame.grid(row = 1, column = 0, sticky=tk.NSEW)
self.search_label.grid(row = 0, column = 0, sticky=tk.NW)
self.search_bar.grid(row = 0, column = 1, sticky=tk.NE)
self.search_results_listbox.grid(row = 1, column = 0, columnspan = 2, sticky=tk.NSEW, pady = 5)
self.search_scroll.grid(row=1, column=2, sticky=(tk.N, tk.S))
#Configure rows and columns of the frame
self.search_frame.columnconfigure(0, weight=1)
self.search_frame.columnconfigure(1, weight=10)
self.search_frame.columnconfigure(1, weight=1)
self.search_frame.rowconfigure(0, weight=1)
self.search_frame.rowconfigure(1, weight = 10)
#########################################################
# Current Tool Frame #
#########################################################
#Create the elements of the current tool frame
self.current_tool_frame = ttk.Frame(overall_frame, padding='0.01i')
self.current_tool_lbl = ttk.Label(self.current_tool_frame, text="Current Tool: {}".format(self.tool_name), justify=tk.LEFT) # , font=("Helvetica", 12, "bold")
self.view_code_button = ttk.Button(self.current_tool_frame, text="View Code", width=12, command=self.view_code)
#Define layout of the frame
self.view_code_button.grid(row=0, column=1, sticky=tk.E)
self.current_tool_lbl.grid(row=0, column=0, sticky=tk.W)
self.current_tool_frame.grid(row=0, column=0, columnspan = 2, sticky=tk.NSEW)
#Configure rows and columns of the frame
self.current_tool_frame.columnconfigure(0, weight=1)
self.current_tool_frame.columnconfigure(1, weight=1)
#########################################################
# Args Frame #
#########################################################
# #Create the elements of the tool arguments frame
# self.arg_scroll = ttk.Scrollbar(overall_frame, orient='vertical')
# self.arg_canvas = tk.Canvas(overall_frame, bd=0, highlightthickness=0, yscrollcommand=self.arg_scroll.set)
# self.arg_scroll.config(command=self.arg_canvas.yview) #self.arg_scroll scrolls over self.arg_canvas
# self.arg_scroll_frame = ttk.Frame(self.arg_canvas) # create a frame inside the self.arg_canvas which will be scrolled with it
# self.arg_scroll_frame_id = self.arg_canvas.create_window(0, 0, window=self.arg_scroll_frame, anchor="nw")
# #Define layout of the frame
# self.arg_scroll.grid(row = 1, column = 1, sticky = (tk.NS, tk.E))
# self.arg_canvas.grid(row = 1, column = 0, sticky = tk.NSEW)
# # reset the view
# self.arg_canvas.xview_moveto(0)
# self.arg_canvas.yview_moveto(0)
# #Add bindings
# self.arg_scroll_frame.bind('<Configure>', self.configure_arg_scroll_frame)
# self.arg_canvas.bind('<Configure>', self.configure_arg_canvas)
self.arg_scroll_frame = ttk.Frame(overall_frame, padding='0.0i')
self.arg_scroll_frame.grid(row=1, column=0, sticky=tk.NSEW)
self.arg_scroll_frame.columnconfigure(0, weight=1)
#########################################################
# Buttons Frame #
#########################################################
#Create the elements of the buttons frame
buttons_frame = ttk.Frame(overall_frame, padding='0.1i')
self.run_button = ttk.Button(buttons_frame, text="Run", width=8, command=self.run_tool)
self.quit_button = ttk.Button(buttons_frame, text="Cancel", width=8, command=self.cancel_operation)
self.help_button = ttk.Button(buttons_frame, text="Help", width=8, command=self.tool_help_button)
#Define layout of the frame
self.run_button.grid(row=0, column=0)
self.quit_button.grid(row=0, column=1)
self.help_button.grid(row = 0, column = 2)
buttons_frame.grid(row=2, column=0, columnspan = 2, sticky=tk.E)
#########################################################
# Output Frame #
#########################################################
#Create the elements of the output frame
output_frame = ttk.Frame(overall_frame)
outlabel = ttk.Label(output_frame, text="Output:", justify=tk.LEFT)
self.out_text = ScrolledText(output_frame, width=63, height=15, wrap=tk.NONE, padx=7, pady=7, exportselection = 0)
output_scrollbar = ttk.Scrollbar(output_frame, orient=tk.HORIZONTAL, command = self.out_text.xview)
self.out_text['xscrollcommand'] = output_scrollbar.set
#Retreive and insert the text for the current tool
k = wbt.tool_help(self.tool_name)
self.out_text.insert(tk.END, k)
#Define layout of the frame
outlabel.grid(row=0, column=0, sticky=tk.NW)
self.out_text.grid(row=1, column=0, sticky=tk.NSEW)
output_frame.grid(row=3, column=0, columnspan = 2, sticky=(tk.NS, tk.E))
output_scrollbar.grid(row=2, column=0, sticky=(tk.W, tk.E))
#Configure rows and columns of the frame
self.out_text.columnconfigure(0, weight=1)
output_frame.columnconfigure(0, weight=1)
# Add the binding
if _platform == "darwin":
self.out_text.bind("<Command-Key-a>", self.select_all)
else:
self.out_text.bind("<Control-Key-a>", self.select_all)
#########################################################
# Progress Frame #
#########################################################
#Create the elements of the progress frame
progress_frame = ttk.Frame(overall_frame, padding='0.1i')
self.progress_label = ttk.Label(progress_frame, text="Progress:", justify=tk.LEFT)
self.progress_var = tk.DoubleVar()
self.progress = ttk.Progressbar(progress_frame, orient="horizontal", variable=self.progress_var, length=200, maximum=100)
#Define layout of the frame
self.progress_label.grid(row=0, column=0, sticky=tk.E, padx=5)
self.progress.grid(row=0, column=1, sticky=tk.E)
progress_frame.grid(row=4, column=0, columnspan = 2, sticky=tk.SE)
#########################################################
# Tool Selection #
#########################################################
# Select the appropriate tool, if specified, otherwise the first tool
self.tool_tree.focus(self.tool_name)
self.tool_tree.selection_set(self.tool_name)
self.tool_tree.event_generate("<<TreeviewSelect>>")
#########################################################
# Menus #
#########################################################
menubar = tk.Menu(self)
self.filemenu = tk.Menu(menubar, tearoff=0)
self.filemenu.add_command(label="Set Working Directory", command=self.set_directory)
self.filemenu.add_command(label="Locate WhiteboxTools exe", command=self.select_exe)
self.filemenu.add_command(label="Refresh Tools", command=self.refresh_tools)
wbt.set_compress_rasters(True)
self.filemenu.add_command(label="Do Not Compress Output TIFFs", command=self.update_compress)
self.filemenu.add_separator()
self.filemenu.add_command(label="Exit", command=self.quit)
menubar.add_cascade(label="File", menu=self.filemenu)
editmenu = tk.Menu(menubar, tearoff=0)
editmenu.add_command(label="Cut", command=lambda: self.focus_get().event_generate("<<Cut>>"))
editmenu.add_command(label="Copy", command=lambda: self.focus_get().event_generate("<<Copy>>"))
editmenu.add_command(label="Paste", command=lambda: self.focus_get().event_generate("<<Paste>>"))
menubar.add_cascade(label="Edit ", menu=editmenu)
helpmenu = tk.Menu(menubar, tearoff=0)
helpmenu.add_command(label="About", command=self.help)
helpmenu.add_command(label="License", command=self.license)
menubar.add_cascade(label="Help ", menu=helpmenu)
self.master.config(menu=menubar)
def update_compress(self):
if wbt.get_compress_rasters():
wbt.set_compress_rasters(False)
self.filemenu.entryconfig(3, label = "Compress Output TIFFs")
else:
wbt.set_compress_rasters(True)
self.filemenu.entryconfig(3, label = "Do Not Compress Output TIFFs")
def get_toolboxes(self):
toolboxes = set()
for item in wbt.toolbox().splitlines(): # run wbt.toolbox with no tool specified--returns all
if item:
tb = item.split(":")[1].strip()
toolboxes.add(tb)
return sorted(toolboxes)
def sort_toolboxes(self):
self.upper_toolboxes = []
self.lower_toolboxes = []
for toolbox in self.toolbox_list:
if toolbox.find('/') == (-1): #Does not contain a subtoolbox, i.e. does not contain '/'
self.upper_toolboxes.append(toolbox) #add to both upper toolbox list and lower toolbox list
self.lower_toolboxes.append(toolbox)
else: #Contains a subtoolbox
self.lower_toolboxes.append(toolbox) #add to only the lower toolbox list
self.upper_toolboxes = sorted(self.upper_toolboxes) #sort both lists alphabetically