-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfmgui.py
1770 lines (1585 loc) · 54.2 KB
/
fmgui.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
# QT GUI routines for filemapper
# Copyright(C) 2016 Darrick J. Wong
# Licensed under GPLv2.
import sys
try:
from PyQt5 import QtGui, uic, QtCore, QtWidgets, Qt
print("Loading qt5...")
except:
from PyQt4 import QtGui, uic, QtCore, Qt
from PyQt4 import QtGui as QtWidgets
print("Loading qt4...")
import fmcli
import datetime
import fmdb
import math
import os.path
import json
import base64
from abc import ABCMeta, abstractmethod
import dateutil.parser
null_model = QtCore.QModelIndex()
bold_font = QtGui.QFont()
bold_font.setBold(True)
def addReturnPressedEvents(widget):
'''Add a returnPressed event to a Qt widget.'''
class ReturnKeyEater(QtCore.QObject):
__rpsig = QtCore.pyqtSignal()
def __init__(self, widget):
super(ReturnKeyEater, self).__init__(widget)
self.widget = widget
self.widget.returnPressed = self.__rpsig
def eventFilter(self, obj, event):
if event.type() == QtCore.QEvent.KeyRelease and \
event.key() in [QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter]:
self.__rpsig.emit()
return True
return False
m = ReturnKeyEater(widget)
widget.installEventFilter(m)
def sort_dentry(dentry):
if dentry.type == fmdb.INO_TYPE_DIR:
return '0' + dentry.name
else:
return '1' + dentry.name
class MessagePump(object):
'''Helper class to prime the Qt message queue periodically.'''
def __init__(self, on_fn, off_fn):
self.last = None
self.interval = None
self.i_start = datetime.timedelta(seconds = 1)
self.i_run = datetime.timedelta(milliseconds = 50)
self.on_fn = on_fn
self.off_fn = off_fn
def start(self):
'''Set ourselves up for periodic message pumping.'''
self.last = datetime.datetime.today()
self.interval = self.i_start
def pump(self):
'''Actually pump messages.'''
now = datetime.datetime.today()
if now > self.last + self.interval:
if self.interval == self.i_start:
self.on_fn()
self.interval = self.i_run
QtWidgets.QApplication.processEvents()
self.last = now
def stop(self):
'''Tear down message pumping.'''
self.off_fn()
self.last = None
self.interval = None
## Data models
class ExtentTableModel(QtCore.QAbstractTableModel):
'''Render and highlight an extent table.'''
def __init__(self, fs, data, units, rows_to_show=500, parent=None, *args):
super(ExtentTableModel, self).__init__(parent, *args)
self.__data = data
self.headers = ['Physical Offset', 'Logical Offset', \
'Length', 'Flags', 'Type', 'Path']
self.header_map = [
lambda x: fmcli.format_size(self.units, x.p_off),
lambda x: fmcli.format_size(self.units, x.l_off),
lambda x: fmcli.format_size(self.units, x.length),
lambda x: fmdb.extent_flagstr(x),
lambda x: fmdb.extent_typestr(x),
lambda x: x.path if x.path != '' else fs.pathsep
]
self.sort_keys = [
lambda x: x.p_off,
lambda x: -1 if x.l_off is None else x.l_off,
lambda x: x.length,
lambda x: fmdb.extent_flagstr(x),
lambda x: fmdb.extent_typestr(x),
lambda x: x.path,
]
self.align_map = [
QtCore.Qt.AlignRight,
QtCore.Qt.AlignRight,
QtCore.Qt.AlignRight,
QtCore.Qt.AlignLeft,
QtCore.Qt.AlignLeft,
QtCore.Qt.AlignLeft,
]
self.units = units
self.rows_to_show = rows_to_show
self.rows = min(rows_to_show, len(data))
self.name_highlight = None
def change_units(self, new_units):
'''Change the display units of the size and length columns.'''
self.units = new_units
tl = self.createIndex(0, 0)
br = self.createIndex(len(self.__data) - 1, 2)
self.dataChanged.emit(tl, br)
def revise(self, new_data):
'''Update the extent table and redraw.'''
olen = self.rows
nlen = min(len(new_data), self.rows_to_show)
self.rows = nlen
parent = self.createIndex(-1, -1)
self.layoutAboutToBeChanged.emit()
if olen > nlen:
self.beginRemoveRows(parent, nlen, olen)
elif nlen > olen:
self.beginInsertRows(parent, olen, nlen)
self.__data = new_data
if olen > nlen:
self.endRemoveRows()
elif nlen > olen:
self.endInsertRows()
tl = self.createIndex(0, 0)
br = self.createIndex(olen - 1, len(self.headers) - 1)
self.dataChanged.emit(tl, br)
self.layoutChanged.emit()
def canFetchMore(self, parent):
return self.rows < len(self.__data)
def fetchMore(self, parent):
'''Reduce load times by rendering subsets selectively.'''
nlen = min(len(self.__data) - self.rows, self.rows_to_show)
self.beginInsertRows(parent, self.rows, self.rows + nlen)
self.rows += nlen
self.endInsertRows()
def rowCount(self, parent):
if not parent.isValid():
return self.rows
return 0
def columnCount(self, parent):
return len(self.headers)
def data(self, index, role):
def is_name_highlighted(name):
if self.name_highlight is None:
return False
return name in self.name_highlight
if not index.isValid():
return None
i = index.row()
j = index.column()
row = self.__data[i]
if role == QtCore.Qt.DisplayRole:
return self.header_map[j](row)
elif role == QtCore.Qt.FontRole:
if is_name_highlighted(row.path):
return bold_font
return None
elif role == QtCore.Qt.TextAlignmentRole:
return self.align_map[j]
return None
def headerData(self, col, orientation, role):
if orientation == QtCore.Qt.Horizontal and \
role == QtCore.Qt.DisplayRole:
return self.headers[col]
return None
def highlight_names(self, names = None):
'''Highlight rows corresponding to some FS paths.'''
self.name_highlight = names
# Skip the re-render since we're just about to requery anyway.
def extents(self, rows):
'''Retrieve a range of extents.'''
if rows is None or len(rows) == 0:
for r in self.__data:
yield r
return
for r in rows:
yield self.__data[r]
def inodes_extents(self, inodes):
'''Retrieve a range of extents for some inodes.'''
if inodes is None or len(inodes) == 0:
return
for r in self.__data:
if r.ino in inodes:
yield r
def extent_count(self):
'''Return the number of rows in the dataset.'''
return len(self.__data)
def sort(self, column, order):
if column < 0:
return
self.__data.sort(key = self.sort_keys[column], reverse = order == 1)
tl = self.createIndex(0, 0)
br = self.createIndex(self.rows - 1, len(self.headers) - 1)
self.dataChanged.emit(tl, br)
class InodeTableModel(QtCore.QAbstractTableModel):
'''Render and highlight an inode table.'''
def __init__(self, fs, data, units, rows_to_show=500, parent=None, *args):
super(InodeTableModel, self).__init__(parent, *args)
self.__data = data
self.fs = fs
self.headers = ['Inode', 'Extents', \
'Travel Score', 'Type', 'Size', 'Last Access', \
'Creation', 'Last Metadata Change', 'Last Data Change', \
'Paths']
self.header_map = [
lambda x: fmcli.format_number(fmcli.units_none, x.ino),
lambda x: fmcli.format_number(fmcli.units_none, x.nr_extents),
lambda x: fmcli.format_size(self.units, x.travel_score),
lambda x: fmdb.inode_typestr(x),
lambda x: fmcli.format_size(self.units, x.size),
lambda x: fmcli.posix_timestamp_str(x.atime, True),
lambda x: fmcli.posix_timestamp_str(x.crtime, True),
lambda x: fmcli.posix_timestamp_str(x.ctime, True),
lambda x: fmcli.posix_timestamp_str(x.mtime, True),
lambda x: self.fs.pathsep if x.path == '' else x.path,
]
self.sort_keys = [
lambda x: x.ino,
lambda x: -1 if x.nr_extents is None else x.nr_extents,
lambda x: -1 if x.travel_score is None else x.travel_score,
lambda x: fmdb.inode_typestr(x),
lambda x: -1 if x.size is None else x.size,
lambda x: -1 if x.atime is None else x.atime,
lambda x: -1 if x.crtime is None else x.crtime,
lambda x: -1 if x.ctime is None else x.ctime,
lambda x: -1 if x.mtime is None else x.mtime,
lambda x: x.path,
]
self.align_map = [
QtCore.Qt.AlignRight,
QtCore.Qt.AlignRight,
QtCore.Qt.AlignRight,
QtCore.Qt.AlignLeft,
QtCore.Qt.AlignRight,
QtCore.Qt.AlignRight,
QtCore.Qt.AlignRight,
QtCore.Qt.AlignRight,
QtCore.Qt.AlignRight,
QtCore.Qt.AlignLeft,
]
self.units = units
self.rows_to_show = rows_to_show
self.rows = min(rows_to_show, len(data))
self.name_highlight = None
def change_units(self, new_units):
'''Change the display units of the size and length columns.'''
self.units = new_units
tl = self.createIndex(0, 2)
br = self.createIndex(len(self.__data) - 1, 2)
self.dataChanged.emit(tl, br)
def revise(self, new_data):
'''Update the inode table and redraw.'''
olen = self.rows
nlen = min(len(new_data), self.rows_to_show)
self.rows = nlen
parent = self.createIndex(-1, -1)
self.layoutAboutToBeChanged.emit()
if olen > nlen:
self.beginRemoveRows(parent, nlen, olen)
elif nlen > olen:
self.beginInsertRows(parent, olen, nlen)
self.__data = new_data
if olen > nlen:
self.endRemoveRows()
elif nlen > olen:
self.endInsertRows()
tl = self.createIndex(0, 0)
br = self.createIndex(olen - 1, len(self.headers) - 1)
self.dataChanged.emit(tl, br)
self.layoutChanged.emit()
def canFetchMore(self, parent):
return self.rows < len(self.__data)
def fetchMore(self, parent):
'''Reduce load times by rendering subsets selectively.'''
nlen = min(len(self.__data) - self.rows, self.rows_to_show)
self.beginInsertRows(parent, self.rows, self.rows + nlen)
self.rows += nlen
self.endInsertRows()
def rowCount(self, parent):
if not parent.isValid():
return self.rows
return 0
def columnCount(self, parent):
return len(self.headers)
def data(self, index, role):
def is_name_highlighted(name):
if self.name_highlight is None:
return False
return name in self.name_highlight
if not index.isValid():
return None
i = index.row()
j = index.column()
row = self.__data[i]
if role == QtCore.Qt.DisplayRole:
return self.header_map[j](row)
elif role == QtCore.Qt.FontRole:
if is_name_highlighted(row.path):
return bold_font
return None
elif role == QtCore.Qt.TextAlignmentRole:
return self.align_map[j]
return None
def headerData(self, col, orientation, role):
if orientation == QtCore.Qt.Horizontal and \
role == QtCore.Qt.DisplayRole:
return self.headers[col]
return None
def highlight_names(self, names = None):
'''Highlight rows corresponding to some FS paths.'''
self.name_highlight = names
# Skip the re-render since we're just about to requery anyway.
# XXX: are we?
def inodes(self, rows):
'''Retrieve a range of extents.'''
if rows is None or len(rows) == 0:
for r in self.__data:
yield r
return
for r in rows:
yield self.__data[r]
def inode_count(self):
'''Return the number of rows in the dataset.'''
return len(self.__data)
def sort(self, column, order):
if column < 0:
return
self.__data.sort(key = self.sort_keys[column], reverse = order == 1)
tl = self.createIndex(0, 0)
br = self.createIndex(self.rows - 1, len(self.headers) - 1)
self.dataChanged.emit(tl, br)
class FsTreeNode(object):
'''A node in the recorded filesystem.'''
def __init__(self, path, ino, type, load_fn = None, parent = None, fs = None):
if load_fn is None and parent is None:
raise ValueError('Supply a dentry loading function or a parent node.')
if fs is None and parent is None:
raise ValueError('Supply a FS summary object or a parent node.')
self.path = path
self.type = type
self.ino = ino
self.parent = parent
if load_fn is not None:
self.load_fn = load_fn
else:
self.load_fn = parent.load_fn
if fs is not None:
self.fs = fs
else:
self.fs = parent.fs
self.loaded = False
self.children = None
self.__row = None
if self.type != fmdb.INO_TYPE_DIR:
self.loaded = True
self.children = []
def load(self):
'''Query the database for child nodes.'''
if self.loaded:
return
self.loaded = True
self.children = [FsTreeNode(self.path + self.fs.pathsep + de.name, de.ino, de.type, parent = self) for de in self.load_fn(self.path)]
def row(self):
if self.__row is None:
if self.parent is None:
self.__row = 0
else:
self.__row = self.parent.children.index(self)
return self.__row
def hasChildren(self):
return self.type == fmdb.INO_TYPE_DIR
class FsTreeModel(QtCore.QAbstractItemModel):
'''Model the filesystem tree recorded in the database.'''
def __init__(self, fs, root, parent=None, *args):
super(FsTreeModel, self).__init__(parent, *args)
self.root = root
self.headers = ['Name']
self.fs = fs
def index(self, row, column, parent):
if not parent.isValid():
return self.createIndex(row, column, self.root)
parent = parent.internalPointer()
parent.load()
return self.createIndex(row, column, parent.children[row])
def root_index(self):
'''Return the index of the root of the model.'''
return self.createIndex(0, 0, self.root)
def parent(self, index):
'''Create an index for the parent of an indexed cell, from
the perspective of the grandparent node.'''
if not index.isValid():
return null_model
node = index.internalPointer()
if node.parent is None:
return null_model
return self.createIndex(node.parent.row(), 0, node.parent)
def hasChildren(self, parent):
if not parent.isValid():
return True
node = parent.internalPointer()
return node.hasChildren()
def rowCount(self, parent):
if not parent.isValid():
return 1
node = parent.internalPointer()
node.load()
return len(node.children)
def columnCount(self, parent):
return len(self.headers)
def data(self, index, role):
if not index.isValid():
return None
node = index.internalPointer()
if role == QtCore.Qt.DisplayRole:
node.load()
if index.column() == 0:
if len(node.path) == 0:
return self.fs.pathsep
r = node.path.rindex(self.fs.pathsep)
return node.path[r + 1:]
else:
return node.ino
elif role == QtCore.Qt.DecorationRole:
if node.type == fmdb.INO_TYPE_DIR:
return QtGui.QIcon.fromTheme('folder')
else:
return QtGui.QIcon.fromTheme('text-x-generic')
return None
def headerData(self, col, orientation, role):
if orientation == QtCore.Qt.Horizontal and \
role == QtCore.Qt.DisplayRole:
return self.headers[col]
return None
class ChecklistModel(QtCore.QAbstractTableModel):
'''A list model for checkable items.'''
def __init__(self, items, parent=None, *args):
super(ChecklistModel, self).__init__(parent, *args)
self.rows = items
def rowCount(self, parent):
return len(self.rows)
def columnCount(self, parent):
return 1
def data(self, index, role):
i = index.row()
j = index.column()
if j != 0:
return None
if role == QtCore.Qt.DisplayRole:
return self.rows[i][0]
elif role == QtCore.Qt.CheckStateRole:
return QtCore.Qt.Checked if self.rows[i][1] else QtCore.Qt.Unchecked
else:
return None
def flags(self, index):
return super(ChecklistModel, self).flags(index) | QtCore.Qt.ItemIsUserCheckable
def setData(self, index, value, role):
if role != QtCore.Qt.CheckStateRole:
return None
row = index.row()
# N.B. Weird comparison because Python2 returns QVariant, not bool
self.rows[row][1] = not (value == False)
return True
def items(self):
return self.rows
class OverviewModel(QtCore.QObject):
'''Render the overview into a text field.'''
rendered = QtCore.pyqtSignal()
def __init__(self, fmdb, ctl, precision = 65536, parent = None, yield_fn = None):
super(OverviewModel, self).__init__(parent)
self.fmdb = fmdb
self.fs = self.fmdb.query_summary()
self.ctl = ctl
self.ctl.resizeEvent = self.resize_ctl
self.length = None
self.zoom = 1.0
self.precision = precision
self.overview_big = None
self.rst = QtCore.QTimer()
self.rst.timeout.connect(self.delayed_resize)
self.range_highlight = None
self.yield_fn = yield_fn
self.auto_size = True
self.has_rendered = False
self.heatmap = True
self.resize_viewport()
def load(self):
'''Query the DB for the high-res overview data.'''
olen = min(self.precision, self.fs.total_bytes // self.fs.block_size)
self.fmdb.set_overview_length(olen)
self.overview_big = [ov for ov in self.fmdb.query_overview()]
self.has_rendered = False
def set_zoom(self, zoom):
'''Set the zoom factor for the overview.'''
new_as = True
if type(zoom) == int or type(zoom) == float:
new_as = False
new_zoom = 1.0
new_length = int(float(self.fs.total_bytes) / zoom)
elif type(zoom) == str:
if zoom[-1] == '%':
new_zoom = float(zoom[:-1]) / 100.0
new_length = 0
else:
new_as = False
new_zoom = 1.0
cell_length = fmcli.s2p(self.fs, zoom)
new_length = int(float(self.fs.total_bytes) / cell_length)
else:
raise ValueError("Unknown zoom factor '%s'" % zoom)
self.auto_size = new_as
self.zoom = new_zoom
self.length = new_length
self.resize_viewport()
self.render()
def total_length(self):
'''The total length of the overview.'''
return self.length * self.zoom
def render_html(self, length):
'''Render the overview for a given length.'''
def is_highlighted(cell):
if range_highlight is None:
return False
for start, end in range_highlight:
if cell >= start and cell <= end:
return True
return False
t0 = datetime.datetime.today()
if self.overview_big is None:
return None
bgcolor = fmdb.color(255, 255, 255)
userdatacolor = fmdb.color(255, 99, 71)
filemetacolor = fmdb.color(173, 255, 47)
fsmetacolor = fmdb.color(136, 206, 255)
freespcolor = fmdb.color(238, 245, 255)
olen = int(length)
o2s = float(len(self.overview_big)) / olen
ov_str = []
t1 = datetime.datetime.today()
old_style_str = None
for i in range(0, olen):
x = int(round(i * o2s))
y = int(round((i + 1) * o2s))
ss = self.overview_big[x:y]
rh = self.range_highlight[x:y] if self.range_highlight is not None else [0]
ovs = fmdb.overview_block(self.fmdb.get_extent_types_to_show())
for s in ss:
ovs.add(s)
if sum(rh) > 0:
style_str = 'background: #e0e0e0; font-weight: bold;'
else:
if self.heatmap:
color = ovs.to_color(bgcolor, \
userdatacolor, filemetacolor, \
fsmetacolor, freespcolor)
else:
color = None
if color is None:
style_str = None
else:
style_str = 'background: %s;' % (color.html())
if old_style_str != style_str:
if old_style_str is not None:
ov_str.append('</span>')
if style_str is not None:
ov_str.append('<span style="%s">' % style_str)
ov_str.append(ovs.to_letter())
old_style_str = style_str
if old_style_str is not None:
ov_str.append('</span>')
t2 = datetime.datetime.today()
fmdb.print_times('render', [t0, t1, t2])
return ''.join(ov_str)
def render(self):
'''Render the overview into the text view.'''
html = self.render_html(int(self.length * self.zoom))
if html is None:
return
cursor = self.ctl.textCursor()
start = cursor.selectionStart()
end = cursor.selectionEnd()
vs = self.ctl.verticalScrollBar()
old_v = vs.value()
old_max = vs.maximum()
self.ctl.setText(html)
if old_max > 0:
if vs.maximum() == old_max:
vs.setValue(old_v)
else:
vs.setValue(int(vs.maximum() * float(old_v) / old_max))
self.rendered.emit()
self.has_rendered = True
def resize_ctl(self, event):
'''Handle the resizing of the text view control.'''
QtWidgets.QTextEdit.resizeEvent(self.ctl, event)
if self.resize_viewport():
self.rst.start(40)
def font_changed(self):
'''Call this if the font changes.'''
if self.resize_viewport():
self.render()
def resize_viewport(self):
'''Recalculate the overview size.'''
sz = self.ctl.viewport().size()
qfm = QtGui.QFontMetrics(self.ctl.document().defaultFont())
overview_font_width = qfm.width('M')
overview_font_height = qfm.height()
# Cheat with the textedit width/height -- use one less
# column than we probably could, and force wrapping at
# that column.
w = (sz.width() // overview_font_width)
h = (sz.height() // overview_font_height) - 1
#print("overview: %d x %d vs. %d x %d" % (sz.width(), sz.height(), overview_font_width, overview_font_height))
self.ctl.setLineWrapColumnOrWidth(w)
#print("overview; %f x %f = %f" % (w, h, w * h))
if self.auto_size:
self.length = w * h
return self.auto_size or not self.has_rendered
def delayed_resize(self):
self.rst.stop()
self.render()
def highlight_ranges(self, ranges):
'''Highlight a range of physical extents in the overview.'''
old_highlight = self.range_highlight
# Figure out which ranges we're playing with
olen = min(self.precision, self.fs.total_bytes // self.fs.block_size)
self.fmdb.set_overview_length(olen)
# Compress that into a set
rset = set()
n = 0
for x in self.fmdb.pick_bytes(ranges):
if type(x) == int:
start = end = x
else:
start, end = x
for x in range(start, end + 1):
rset.add(x)
if n > 1000:
self.yield_fn()
n = 0
n += 1
self.range_highlight = [(1 if n in rset else 0) for n in range(0, olen)]
if old_highlight == self.range_highlight:
return
self.render()
## Query classes
class FmQuery(object):
'''Abstract base class to manage query context and UI.'''
def __init__(self, label, ctl, query_fn):
self.label = label
self.ctl = ctl
self.query_fn = query_fn
@abstractmethod
def load_query(self):
'''Load ourselves into the UI.'''
raise NotImplementedError()
@abstractmethod
def save_query(self):
'''Save UI contents.'''
raise NotImplementedError()
@abstractmethod
def parse_query(self):
'''Parse query contents into some meaningful form.'''
raise NotImplementedError()
def run_query(self):
'''Run a query.'''
args = self.parse_query()
#print("QUERY:", self.label, args)
self.query_fn(args)
@abstractmethod
def export_state(self):
'''Export state data for serializeation.'''
raise NotImplementedError()
@abstractmethod
def import_state(self, data):
'''Import state data for serialization.'''
raise NotImplementedError()
def summarize(self):
'''Summarize the state of this query as a string.'''
return self.label + ': '
class StringQuery(FmQuery):
'''Handle queries that are free-form text.'''
def __init__(self, label, ctl, query_fn, edit_string = '', history = None, parent=None, *args):
super(StringQuery, self).__init__(label, ctl, query_fn)
if history is None:
self.history = []
else:
self.history = history
self.edit_string = edit_string
def load_query(self):
self.ctl.clear()
self.ctl.addItems(self.history)
if self.edit_string in self.history:
self.ctl.setCurrentIndex(self.history.index(self.edit_string))
else:
self.ctl.setEditText(self.edit_string)
self.ctl.show()
def save_query(self):
self.ctl.hide()
self.edit_string = str(self.ctl.currentText())
def parse_query(self):
a = str(self.ctl.currentText())
self.edit_string = a
self.add_to_history(a)
return fmcli.split_unescape(str(a), ' ', ('"', "'"))
def add_to_history(self, string):
'''Add a string to the history.'''
if len(self.history) > 0 and self.history[0] == string:
return
if string in self.history:
self.history.remove(string)
r = self.ctl.findText(string)
if r >= 0:
self.ctl.removeItem(r)
self.history.insert(0, string)
self.ctl.insertItem(0, string)
self.ctl.setCurrentIndex(self.history.index(string))
def export_state(self):
return {'edit_string': str(self.edit_string), 'history': self.history[:100]}
def import_state(self, data):
self.edit_string = data['edit_string']
self.history = data['history']
def summarize(self):
x = super(StringQuery, self).summarize()
return x + self.edit_string
class ChecklistQuery(FmQuery):
'''Handle queries comprising a selection of discrete items.'''
def __init__(self, label, ctl, query_fn, items, parent=None, *args):
super(ChecklistQuery, self).__init__(label, ctl, query_fn)
self.items = items
self.model = ChecklistModel(items)
def load_query(self):
self.ctl.setModel(self.model)
self.ctl.show()
def save_query(self):
self.ctl.hide()
def parse_query(self):
return self.items
def export_state(self):
return [{'label': x[0], 'state': x[1]} for x in self.items]
def import_state(self, data):
for d in data:
for i in self.items:
if i[0] == d['label']:
i[1] = d['state']
break
def summarize(self):
x = super(StringQuery, self).summarize()
return x + ', '.join([x for x in self.items if x[1]])
class TimestampQuery(FmQuery):
'''Handle queries comprising a range of timestamps.'''
def __init__(self, label, ctl, query_fn, start_ctl, end_ctl, range_ctl, start = None, end = None, range_enabled = False, parent=None, *args):
super(TimestampQuery, self).__init__(label, ctl, query_fn)
self.nowgmt = datetime.datetime.utcnow().replace(microsecond = 0, tzinfo = fmdb.tz_gmt)
self.start = self.nowgmt if start is None else start
self.end = self.nowgmt if end is None else end
self.range_enabled = range_enabled
self.start_ctl = start_ctl
self.end_ctl = end_ctl
self.range_ctl = range_ctl
def load_query(self):
self.start_ctl.setDateTime(self.start.astimezone(fmdb.tz_local))
self.end_ctl.setDateTime(self.end.astimezone(fmdb.tz_local))
self.range_ctl.setCheckState(QtCore.Qt.Checked if self.range_enabled else QtCore.Qt.Unchecked)
self.ctl.show()
def save_query(self):
self.ctl.hide()
self.parse_query()
def parse_query(self):
def x(d):
return d.dateTime().toPyDateTime().replace(microsecond = 0, tzinfo = fmdb.tz_local).astimezone(fmdb.tz_gmt)
self.range_enabled = self.range_ctl.checkState() == QtCore.Qt.Checked
self.start = x(self.start_ctl)
self.end = x(self.end_ctl)
if self.range_enabled:
return (self.start, self.end)
return self.start
def export_state(self):
a = 'None' if self.start == self.nowgmt else self.start.isoformat()
b = 'None' if self.end == self.nowgmt else self.end.isoformat()
return [a, b, self.range_enabled]
def import_state(self, data):
if data[0] != 'None':
self.start = dateutil.parser.parse(data[0])
if data[1] != 'None':
self.end = dateutil.parser.parse(data[1])
self.range_enabled = data[2] == True
def summarize(self):
x = super(TimestampQuery, self).summarize()
if not self.range_enabled:
return x + fmcli.posix_timestamp_str(self.start, True)
return x + fmcli.posix_timestamp_str(self.start, True) + ' to ' + fmcli.posix_timestamp_str(self.end, True)
## Custom widgets
class XLineEdit(QtWidgets.QLineEdit):
'''QLineEdit with clear button, which appears when user enters text.'''
def __init__(self, parent=None):
super(XLineEdit, self).__init__(parent)
self.layout = QtWidgets.QHBoxLayout(self)
self.image = QtWidgets.QLabel(self)
self.image.setCursor(QtCore.Qt.ArrowCursor)
self.image.setFocusPolicy(QtCore.Qt.NoFocus)
self.image.setStyleSheet("border: none;")
pixmap = QtGui.QIcon.fromTheme('locationbar-erase').pixmap(16, 16)
self.image.setPixmap(pixmap)
self.image.setSizePolicy(
QtWidgets.QSizePolicy.Expanding,
QtWidgets.QSizePolicy.Expanding)
self.image.adjustSize()
self.image.setScaledContents(True)
self.layout.addWidget(
self.image, alignment=QtCore.Qt.AlignRight)
self.textChanged.connect(self.changed)
self.image.hide()
self.image.mouseReleaseEvent = self.clear_mouse_release
qm = self.textMargins()
qm.setRight(qm.right() + 24)
self.setTextMargins(qm)
def clear_mouse_release(self, ev):
QtWidgets.QLabel.mouseReleaseEvent(self.image, ev)
if ev.button() == QtCore.Qt.LeftButton:
self.clear()
def changed(self, text):
if len(text) > 0:
self.image.show()
else:
self.image.hide()
### Validator for the zoom combobox
class ZoomValidator(QtGui.QValidator):
'''Validate a zoom size.'''
def __init__(self, fs, parent = None):
super(ZoomValidator, self).__init__(parent)
self.fs = fs
def validate(self, string, pos = None):
if string == '':
return (QtGui.QValidator.Intermediate, string, pos)
try:
self.try_validate(string)
return (QtGui.QValidator.Acceptable, string, pos)
except:
return (QtGui.QValidator.Invalid, string, pos)
def try_validate(self, zoom):
'''Try to validate the string.'''
if type(zoom) == int or type(zoom) == float:
pass
elif type(zoom) == str:
if zoom[-1] == '%':
zoom = float(zoom[:-1]) / 100.0
else:
cell_length = fmcli.s2p(self.fs, zoom)
zoom = int(self.fs.total_bytes / cell_length)
else:
raise ValueError("Unknown zoom factor '%s'" % zoom)
return zoom
## GUI
class fmgui(QtWidgets.QMainWindow):
'''Manage the GUI widgets and interactions.'''
def __init__(self, fmdbX, histfile=os.path.join(os.path.expanduser('~'), \
'.config', 'fmgui-history')):
super(fmgui, self).__init__()
self.json_version = 1
self.fmdb = fmdbX
try:
uic.loadUi('%s/filemapper.ui' % os.environ['FM_LIB_DIR'], self)
except:
uic.loadUi('filemapper.ui', self)
self.fs = self.fmdb.query_summary()
self.setWindowTitle('%s (%s) - FileMapper' % (self.fs.path, self.fs.fstype))
self.histfile = histfile
self.mp = MessagePump(self.mp_start, self.mp_stop)
# Set up the menu
units = fmcli.units_auto
self.unit_actions = self.menuUnits.actions()
ag = QtWidgets.QActionGroup(self)
for u in self.unit_actions:
u.setActionGroup(ag)
ag.triggered.connect(self.change_units)
self.actionExportExtents.triggered.connect(self.export_extents)
self.actionExportExtents.setIcon(QtGui.QIcon.fromTheme('document-save'))