aboutsummaryrefslogtreecommitdiffstats
path: root/ui/qt/proto_tree.cpp
blob: 80c4607d6885633b8f7a75538e0248a35787b884 (plain)
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
/* proto_tree.cpp
 *
 * Wireshark - Network traffic analyzer
 * By Gerald Combs <gerald@wireshark.org>
 * Copyright 1998 Gerald Combs
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 */

#include <stdio.h>

#include <ui/qt/proto_tree.h>
#include <ui/qt/models/proto_tree_model.h>

#include <epan/ftypes/ftypes.h>
#include <epan/prefs.h>

#include <ui/qt/utils/color_utils.h>
#include <ui/qt/utils/variant_pointer.h>
#include <ui/qt/utils/wireshark_mime_data.h>
#include <ui/qt/widgets/drag_label.h>
#include <ui/qt/widgets/wireshark_file_dialog.h>
#include <ui/qt/show_packet_bytes_dialog.h>
#include <ui/qt/filter_action.h>
#include <ui/all_files_wildcard.h>
#include <ui/alert_box.h>
#include "wireshark_application.h"

#include <QApplication>
#include <QContextMenuEvent>
#include <QDesktopServices>
#include <QHeaderView>
#include <QItemSelectionModel>
#include <QScrollBar>
#include <QStack>
#include <QUrl>
#include <QClipboard>
#include <QWindow>
#include <QMessageBox>

// To do:
// - Fix "apply as filter" behavior.

ProtoTree::ProtoTree(QWidget *parent, epan_dissect_t *edt_fixed) :
    QTreeView(parent),
    proto_tree_model_(new ProtoTreeModel(this)),
    decode_as_(NULL),
    column_resize_timer_(0),
    cap_file_(NULL),
    edt_(edt_fixed)
{
    setAccessibleName(tr("Packet details"));
    // Leave the uniformRowHeights property as-is (false) since items might
    // have multiple lines (e.g. packet comments). If this slows things down
    // too much we should add a custom delegate which handles SizeHintRole
    // similar to PacketListModel::data.
    setHeaderHidden(true);

#if !defined(Q_OS_WIN)
#if defined(Q_OS_MAC)
    QPalette default_pal = QApplication::palette();
    default_pal.setCurrentColorGroup(QPalette::Active);
    QColor hover_color = default_pal.highlight().color();
#else
    QColor hover_color = ColorUtils::alphaBlend(palette().window(), palette().highlight(), 0.5);
#endif

    setStyleSheet(QString(
        "QTreeView:item:hover {"
        "  background-color: %1;"
        "  color: palette(text);"
        "}").arg(hover_color.name(QColor::HexArgb)));
#endif

    // Shrink down to a small but nonzero size in the main splitter.
    int one_em = fontMetrics().height();
    setMinimumSize(one_em, one_em);

    setModel(proto_tree_model_);

    connect(this, SIGNAL(expanded(QModelIndex)), this, SLOT(syncExpanded(QModelIndex)));
    connect(this, SIGNAL(collapsed(QModelIndex)), this, SLOT(syncCollapsed(QModelIndex)));
    connect(this, SIGNAL(doubleClicked(QModelIndex)),
            this, SLOT(itemDoubleClicked(QModelIndex)));

    connect(&proto_prefs_menu_, SIGNAL(showProtocolPreferences(QString)),
            this, SIGNAL(showProtocolPreferences(QString)));
    connect(&proto_prefs_menu_, SIGNAL(editProtocolPreference(preference*,pref_module*)),
            this, SIGNAL(editProtocolPreference(preference*,pref_module*)));

    // resizeColumnToContents checks 1000 items by default. The user might
    // have scrolled to an area with a different width at this point.
    connect(verticalScrollBar(), SIGNAL(sliderReleased()),
            this, SLOT(updateContentWidth()));

    viewport()->installEventFilter(this);
}

void ProtoTree::clear() {
    proto_tree_model_->setRootNode(NULL);
    updateContentWidth();
}

void ProtoTree::closeContextMenu()
{
    ctx_menu_.close();
}

void ProtoTree::protoTreeContextMenu(QContextMenuEvent * event)
{
    QMenu ctxMenu(this);
    QAction * action;

    bool have_subtree = false;
#if 0
    bool have_packet_bytes = false;
#endif

    QModelIndex index = indexAt(event->pos());
    if ( index.isValid() )
    {
        FieldInformation finfo(proto_tree_model_->protoNodeFromIndex(index).protoNode());
        field_info * fi = finfo.fieldInfo();

        bool is_selected = false;

        if (cap_file_ && cap_file_->finfo_selected == fi)
            is_selected = true;
        else if (! window()->findChild<QAction *>("actionViewExpandSubtrees"))
            is_selected = true;

        if ( is_selected )
        {
            if (fi && fi->tree_type != -1) {
                have_subtree = true;
            }
#if 0
            if (fi && fi->ds_tvb) {
                have_packet_bytes = true;
            }
#endif
        }
    }


    action = ctxMenu.addAction(tr("Expand Subtrees"), this, SLOT(expandSubtrees()));
    action->setEnabled(have_subtree);
    action = ctxMenu.addAction(tr("Collapse Subtrees"), this, SLOT(collapseSubtrees()));
    action->setEnabled(have_subtree);
    ctxMenu.addAction(tr("Expand All"), this, SLOT(expandAll()));
    ctxMenu.addAction(tr("Collapse All"), this, SLOT(collapseAll()));
    ctxMenu.addSeparator();

    QMenu *submenu = ctxMenu.addMenu(tr("Copy"));
    submenu->addAction(tr("All Visible Items"), this, SLOT(ctxCopyVisibleItems()));
    action = submenu->addAction(tr("All Visible Selected Tree Items"), this, SLOT(ctxCopyVisibleItems()));
    action->setProperty("selected_tree", qVariantFromValue(true));
    action = submenu->addAction(tr("Desription"), this, SLOT(ctxCopySelectedInfo()));
    action->setProperty("field_type", ProtoTree::Description);
    action = submenu->addAction(tr("Field Name"), this, SLOT(ctxCopySelectedInfo()));
    action->setProperty("field_type", ProtoTree::Name);
    action = submenu->addAction(tr("Value"), this, SLOT(ctxCopySelectedInfo()));
    action->setProperty("field_type", ProtoTree::Value);
    submenu->addSeparator();
    submenu->addAction(tr("As Filter"), this, SLOT(ctxCopyAsFilter()));

    ctxMenu.addSeparator();

    ctxMenu.addAction(tr("Wiki Protocol Page"), this, SLOT(ctxOpenUrlWiki()));
    action = ctxMenu.addAction(tr("Filter Field Reference"), this, SLOT(ctxOpenUrlWiki()));
    action->setProperty("field_reference", qVariantFromValue(true));
    ctxMenu.addMenu(&proto_prefs_menu_);

    QModelIndex idx = indexAt(event->pos());
    FieldInformation finfo(proto_tree_model_->protoNodeFromIndex(idx).protoNode());
    QActionGroup * copyEntries = DataPrinter::copyActions(this, &finfo);
    submenu->addActions(copyEntries->actions());


    // The "text only" header field will not give preferences for the selected protocol.
    // Use parent in this case.
    proto_node *node = proto_tree_model_->protoNodeFromIndex(idx).protoNode();
    while (node && node->finfo && node->finfo->hfinfo && node->finfo->hfinfo->id == hf_text_only)
        node = node->parent;

    FieldInformation pref_finfo(node);
    proto_prefs_menu_.setModule(pref_finfo.moduleName());


    ctxMenu.exec(event->globalPos());
}

void ProtoTree::ctxCopyVisibleItems()
{
    bool selected_tree = false;

    QAction * send = qobject_cast<QAction *>(sender());
    if ( send && send->property("selected_tree").isValid() )
        selected_tree = true;

    QString clip = toString();
    if ( selected_tree && selectionModel()->hasSelection() )
        clip = toString(selectionModel()->selectedIndexes().first());

    if ( clip.length() > 0 )
        wsApp->clipboard()->setText(clip);
}

void ProtoTree::ctxCopyAsFilter()
{
    QModelIndex idx = selectionModel()->selectedIndexes().first();
    FieldInformation finfo(proto_tree_model_->protoNodeFromIndex(idx).protoNode());
    if ( finfo.isValid() )
    {
        epan_dissect_t *edt = cap_file_ ? cap_file_->edt : edt_;
        char *field_filter = proto_construct_match_selected_string(finfo.fieldInfo(), edt);
        QString filter(field_filter);
        wmem_free(Q_NULLPTR, field_filter);

        if ( filter.length() > 0 )
            wsApp->clipboard()->setText(filter);
    }
}

void ProtoTree::ctxCopySelectedInfo()
{
    int val = -1;
    QString clip;
    QAction * send = qobject_cast<QAction *>(sender());
    if ( send && send->property("field_type").isValid() )
        val = send->property("field_type").toInt();

    QModelIndex idx = selectionModel()->selectedIndexes().first();
    FieldInformation finfo(proto_tree_model_->protoNodeFromIndex(idx).protoNode());
    if ( ! finfo.isValid() )
        return;

    switch (val)
    {
    case ProtoTree::Name:
        clip.append(finfo.headerInfo().abbreviation);
        break;

    case ProtoTree::Description:
        if ( finfo.fieldInfo()->rep && strlen(finfo.fieldInfo()->rep->representation) > 0 )
            clip.append(finfo.fieldInfo()->rep->representation);
        break;

    case ProtoTree::Value:
        if ( edt_ )
        {
            gchar* field_str = get_node_field_value(finfo.fieldInfo(), edt_);
            clip.append(field_str);
            g_free(field_str);
        }
        break;
    default:
        break;
    }

    if ( clip.length() > 0 )
        wsApp->clipboard()->setText(clip);
}

void ProtoTree::ctxOpenUrlWiki()
{
    QUrl url;
    bool is_field_reference = false;
    QAction * send = qobject_cast<QAction *>(sender());
    if ( send && send->property("field_reference").isValid() )
        is_field_reference = send->property("field_reference").toBool();
    QModelIndex idx = selectionModel()->selectedIndexes().first();
    FieldInformation finfo(proto_tree_model_->protoNodeFromIndex(idx).protoNode());

    const QString proto_abbrev = proto_registrar_get_abbrev(finfo.headerInfo().id);

    if ( ! is_field_reference )
    {
        int ret = QMessageBox::question(this, wsApp->windowTitleString(tr("Wiki Page for %1").arg(proto_abbrev)),
                                        tr("<p>The Wireshark Wiki is maintained by the community.</p>"
                                        "<p>The page you are about to load might be wonderful, "
                                        "incomplete, wrong, or nonexistent.</p>"
                                        "<p>Proceed to the wiki?</p>"),
                                        QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);

        if (ret != QMessageBox::Yes) return;

        url = QString("https://wiki.wireshark.org/Protocols/%1").arg(proto_abbrev);
    }
    else
    {
        url = QString("https://www.wireshark.org/docs/dfref/%1/%2")
                .arg(proto_abbrev[0])
                .arg(proto_abbrev);
    }

    QDesktopServices::openUrl(url);
}

void ProtoTree::contextMenuEvent(QContextMenuEvent *event)
{
    // We're in a PacketDialog
    if (! window()->findChild<QAction *>("actionViewExpandSubtrees"))
    {
        protoTreeContextMenu(event);
        return;
    }

    ctx_menu_.clear();

    QMenu *main_menu_item, *submenu;
    QAction *action;

    ctx_menu_.addAction(window()->findChild<QAction *>("actionViewExpandSubtrees"));
    ctx_menu_.addAction(window()->findChild<QAction *>("actionViewCollapseSubtrees"));
    ctx_menu_.addAction(window()->findChild<QAction *>("actionViewExpandAll"));
    ctx_menu_.addAction(window()->findChild<QAction *>("actionViewCollapseAll"));
    ctx_menu_.addSeparator();

    action = window()->findChild<QAction *>("actionAnalyzeCreateAColumn");
    ctx_menu_.addAction(action);
    ctx_menu_.addSeparator();

    QModelIndex index = indexAt(event->pos());
    FieldInformation finfo(proto_tree_model_->protoNodeFromIndex(index).protoNode());

    epan_dissect_t *edt = cap_file_ ? cap_file_->edt : edt_;
    char * selectedfilter = proto_construct_match_selected_string(finfo.fieldInfo(), edt);
    bool can_match_selected = proto_can_match_selected(finfo.fieldInfo(), edt);
    main_menu_item = new QMenu(tr("Apply as Filter"), &ctx_menu_);
    QActionGroup * group = FilterAction::createFilterGroup(selectedfilter, false, can_match_selected, &ctx_menu_);
    main_menu_item->addActions(group->actions());
    ctx_menu_.addMenu(main_menu_item);
    main_menu_item = new QMenu(tr("Prepare as Filter"), &ctx_menu_);
    group = FilterAction::createFilterGroup(selectedfilter, true, can_match_selected, &ctx_menu_);
    main_menu_item->addActions(group->actions());
    ctx_menu_.addMenu(main_menu_item);
    if ( selectedfilter )
        wmem_free(Q_NULLPTR, selectedfilter);

    QMenu *main_conv_menu = window()->findChild<QMenu *>("menuConversationFilter");
    conv_menu_.setTitle(main_conv_menu->title());
    conv_menu_.clear();
    foreach (QAction *action, main_conv_menu->actions()) {
        conv_menu_.addAction(action);
    }

    ctx_menu_.addMenu(&conv_menu_);

    colorize_menu_.setTitle(tr("Colorize with Filter"));
    ctx_menu_.addMenu(&colorize_menu_);

    main_menu_item = window()->findChild<QMenu *>("menuFollow");
    submenu = new QMenu(main_menu_item->title(), &ctx_menu_);
    ctx_menu_.addMenu(submenu);
    submenu->addAction(window()->findChild<QAction *>("actionAnalyzeFollowTCPStream"));
    submenu->addAction(window()->findChild<QAction *>("actionAnalyzeFollowUDPStream"));
    submenu->addAction(window()->findChild<QAction *>("actionAnalyzeFollowTLSStream"));
    submenu->addAction(window()->findChild<QAction *>("actionAnalyzeFollowHTTPStream"));
    ctx_menu_.addSeparator();

    main_menu_item = window()->findChild<QMenu *>("menuEditCopy");
    submenu = new QMenu(main_menu_item->title(), &ctx_menu_);
    ctx_menu_.addMenu(submenu);
    submenu->addAction(window()->findChild<QAction *>("actionCopyAllVisibleItems"));
    submenu->addAction(window()->findChild<QAction *>("actionCopyAllVisibleSelectedTreeItems"));
    submenu->addAction(window()->findChild<QAction *>("actionEditCopyDescription"));
    submenu->addAction(window()->findChild<QAction *>("actionEditCopyFieldName"));
    submenu->addAction(window()->findChild<QAction *>("actionEditCopyValue"));
    submenu->addSeparator();

    submenu->addAction(window()->findChild<QAction *>("actionEditCopyAsFilter"));
    submenu->addSeparator();

    QActionGroup * copyEntries = DataPrinter::copyActions(this, &finfo);
    submenu->addActions(copyEntries->actions());

    action = window()->findChild<QAction *>("actionAnalyzeShowPacketBytes");
    ctx_menu_.addAction(action);
    action = window()->findChild<QAction *>("actionFileExportPacketBytes");
    ctx_menu_.addAction(action);

    ctx_menu_.addSeparator();

    action = window()->findChild<QAction *>("actionContextWikiProtocolPage");
    ctx_menu_.addAction(action);
    action = window()->findChild<QAction *>("actionContextFilterFieldReference");
    ctx_menu_.addAction(action);
    ctx_menu_.addMenu(&proto_prefs_menu_);
    ctx_menu_.addSeparator();
    decode_as_ = window()->findChild<QAction *>("actionAnalyzeDecodeAs");
    ctx_menu_.addAction(decode_as_);

    ctx_menu_.addAction(window()->findChild<QAction *>("actionGoGoToLinkedPacket"));
    ctx_menu_.addAction(window()->findChild<QAction *>("actionContextShowLinkedPacketInNewWindow"));

    // The "text only" header field will not give preferences for the selected protocol.
    // Use parent in this case.
    proto_node *node = proto_tree_model_->protoNodeFromIndex(index).protoNode();
    while (node && node->finfo && node->finfo->hfinfo && node->finfo->hfinfo->id == hf_text_only)
        node = node->parent;

    FieldInformation pref_finfo(node);
    proto_prefs_menu_.setModule(pref_finfo.moduleName());

    decode_as_->setData(QVariant::fromValue(true));

    ctx_menu_.exec(event->globalPos());
    decode_as_->setData(QVariant());
}

void ProtoTree::timerEvent(QTimerEvent *event)
{
    if (event->timerId() == column_resize_timer_) {
        killTimer(column_resize_timer_);
        column_resize_timer_ = 0;
        resizeColumnToContents(0);
    } else {
        QTreeView::timerEvent(event);
    }
}

// resizeColumnToContents checks 1000 items by default. The user might
// have scrolled to an area with a different width at this point.
void ProtoTree::keyReleaseEvent(QKeyEvent *event)
{
    if (event->isAutoRepeat()) return;

    switch(event->key()) {
        case Qt::Key_Up:
        case Qt::Key_Down:
        case Qt::Key_PageUp:
        case Qt::Key_PageDown:
        case Qt::Key_Home:
        case Qt::Key_End:
            updateContentWidth();
            break;
        default:
            break;
    }
}

void ProtoTree::updateContentWidth()
{
    if (column_resize_timer_ == 0) {
        column_resize_timer_ = startTimer(0);
    }
}

void ProtoTree::setMonospaceFont(const QFont &mono_font)
{
    mono_font_ = mono_font;
    setFont(mono_font_);
    update();
}

void ProtoTree::foreachTreeNode(proto_node *node, gpointer proto_tree_ptr)
{
    ProtoTree *tree_view = static_cast<ProtoTree *>(proto_tree_ptr);
    ProtoTreeModel *model = qobject_cast<ProtoTreeModel *>(tree_view->model());
    if (!tree_view || !model) {
        return;
    }

    // Expanded state
    if (tree_expanded(node->finfo->tree_type)) {
        ProtoNode expand_node = ProtoNode(node);
        tree_view->expand(model->indexFromProtoNode(expand_node));
    }

    // Related frames
    if (node->finfo->hfinfo->type == FT_FRAMENUM) {
        ft_framenum_type_t framenum_type = (ft_framenum_type_t)GPOINTER_TO_INT(node->finfo->hfinfo->strings);
        tree_view->emitRelatedFrame(node->finfo->value.value.uinteger, framenum_type);
    }

    proto_tree_children_foreach(node, foreachTreeNode, proto_tree_ptr);
}

// We track item expansion using proto.c:tree_is_expanded. QTreeView
// tracks it using QTreeViewPrivate::expandedIndexes. When we're handed
// a new tree, clear expandedIndexes and repopulate it by walking the
// tree and calling QTreeView::expand above.
void ProtoTree::setRootNode(proto_node *root_node) {
    setFont(mono_font_);
    reset(); // clears expandedIndexes.
    proto_tree_model_->setRootNode(root_node);

    disconnect(this, SIGNAL(expanded(QModelIndex)), this, SLOT(syncExpanded(QModelIndex)));
    proto_tree_children_foreach(root_node, foreachTreeNode, this);
    connect(this, SIGNAL(expanded(QModelIndex)), this, SLOT(syncExpanded(QModelIndex)));

    updateContentWidth();
}

void ProtoTree::emitRelatedFrame(int related_frame, ft_framenum_type_t framenum_type)
{
    emit relatedFrame(related_frame, framenum_type);
}

void ProtoTree::autoScrollTo(const QModelIndex &index)
{
    selectionModel()->select(index, QItemSelectionModel::ClearAndSelect);
    if (!index.isValid()) {
        return;
    }

    // ensure item is visible (expanding its parents as needed).
    scrollTo(index);
}

// XXX We select the first match, which might not be the desired item.
void ProtoTree::goToHfid(int hfid)
{
    QModelIndex index = proto_tree_model_->findFirstHfid(hfid);
    autoScrollTo(index);
}

void ProtoTree::selectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
{
    QTreeView::selectionChanged(selected, deselected);
    if (selected.isEmpty()) {
        emit fieldSelected(0);
        return;
    }

    QModelIndex index = selected.indexes().first();
    saveSelectedField(index);

    // Find and highlight the protocol bytes. select above won't call
    // selectionChanged if the current and selected indexes are the same
    // so we do this here.
    FieldInformation finfo(proto_tree_model_->protoNodeFromIndex(index).protoNode(), this);
    if (finfo.isValid()) {
        QModelIndex parent = index;
        while (parent.isValid() && parent.parent().isValid()) {
            parent = parent.parent();
        }
        if (parent.isValid()) {
            FieldInformation parent_finfo(proto_tree_model_->protoNodeFromIndex(parent).protoNode());
            finfo.setParentField(parent_finfo.fieldInfo());
        }
        emit fieldSelected(&finfo);
    }
}

void ProtoTree::syncExpanded(const QModelIndex &index) {
    FieldInformation finfo(proto_tree_model_->protoNodeFromIndex(index).protoNode());
    if (!finfo.isValid()) return;

    /*
     * Nodes with "finfo->tree_type" of -1 have no ett_ value, and
     * are thus presumably leaf nodes and cannot be expanded.
     */
    if (finfo.treeType() != -1) {
        tree_expanded_set(finfo.treeType(), TRUE);
    }
}

void ProtoTree::syncCollapsed(const QModelIndex &index) {
    FieldInformation finfo(proto_tree_model_->protoNodeFromIndex(index).protoNode());
    if (!finfo.isValid()) return;

    /*
     * Nodes with "finfo->tree_type" of -1 have no ett_ value, and
     * are thus presumably leaf nodes and cannot be collapsed.
     */
    if (finfo.treeType() != -1) {
        tree_expanded_set(finfo.treeType(), FALSE);
    }
}

void ProtoTree::expandSubtrees()
{
    if (!selectionModel()->hasSelection()) return;

    QStack<QModelIndex> index_stack;
    index_stack.push(selectionModel()->selectedIndexes().first());

    while (!index_stack.isEmpty()) {
        QModelIndex index = index_stack.pop();
        expand(index);
        int row_count = proto_tree_model_->rowCount(index);
        for (int row = row_count - 1; row >= 0; row--) {
            QModelIndex child = proto_tree_model_->index(row, 0, index);
            if (proto_tree_model_->hasChildren(child)) {
                index_stack.push(child);
            }
        }
    }

    updateContentWidth();
}

void ProtoTree::collapseSubtrees()
{
    if (!selectionModel()->hasSelection()) return;

    QStack<QModelIndex> index_stack;
    index_stack.push(selectionModel()->selectedIndexes().first());

    while (!index_stack.isEmpty()) {
        QModelIndex index = index_stack.pop();
        collapse(index);
        int row_count = proto_tree_model_->rowCount(index);
        for (int row = row_count - 1; row >= 0; row--) {
            QModelIndex child = proto_tree_model_->index(row, 0, index);
            if (proto_tree_model_->hasChildren(child)) {
                index_stack.push(child);
            }
        }
    }

    updateContentWidth();
}

void ProtoTree::expandAll()
{
    for(int i = 0; i < num_tree_types; i++) {
        tree_expanded_set(i, TRUE);
    }
    QTreeView::expandAll();
    updateContentWidth();
}

void ProtoTree::collapseAll()
{
    for(int i = 0; i < num_tree_types; i++) {
        tree_expanded_set(i, FALSE);
    }
    QTreeView::collapseAll();
    updateContentWidth();
}

void ProtoTree::itemDoubleClicked(const QModelIndex &index) {
    FieldInformation finfo(proto_tree_model_->protoNodeFromIndex(index).protoNode());
    if (!finfo.isValid()) return;

    if (finfo.headerInfo().type == FT_FRAMENUM) {
        if (QApplication::queryKeyboardModifiers() & Qt::ShiftModifier) {
            emit openPacketInNewWindow(true);
        } else {
            emit goToPacket(finfo.fieldInfo()->value.value.uinteger);
        }
    } else {
        QString url = finfo.url();
        if (!url.isEmpty()) {
            QDesktopServices::openUrl(QUrl(url));
        }
    }
}

// Select a field and bring it into view. Intended to be called by external
// components (such as the byte view).
void ProtoTree::selectedFieldChanged(FieldInformation *finfo)
{
    if (finfo && finfo->parent() == this) {
        // We only want inbound signals.
        return;
    }

    QModelIndex index = proto_tree_model_->findFieldInformation(finfo);
    setUpdatesEnabled(false);
    // The new finfo might match the current index. Clear our selection
    // so that we force a fresh item selection, so that fieldSelected
    // will in turn be emitted.
    selectionModel()->clearSelection();
    autoScrollTo(index);
    setUpdatesEnabled(true);
}

// Remember the currently focussed field based on:
// - current hf_id (obviously)
// - parent items (to avoid selecting a text item in a different tree)
// - the row of each item
void ProtoTree::saveSelectedField(QModelIndex &index)
{
    selected_hfid_path_.clear();
    QModelIndex save_index = index;
    while (save_index.isValid()) {
        FieldInformation finfo(proto_tree_model_->protoNodeFromIndex(save_index).protoNode());
        if (!finfo.isValid()) break;
        selected_hfid_path_.prepend(QPair<int,int>(save_index.row(), finfo.headerInfo().id));
        save_index = save_index.parent();
    }
}

// Try to focus a tree item which was previously also visible
void ProtoTree::restoreSelectedField()
{
    if (selected_hfid_path_.isEmpty()) return;

    QModelIndex cur_index = QModelIndex();
    QPair<int,int> path_entry;
    foreach (path_entry, selected_hfid_path_) {
        int row = path_entry.first;
        int hf_id = path_entry.second;
        cur_index = proto_tree_model_->index(row, 0, cur_index);
        FieldInformation finfo(proto_tree_model_->protoNodeFromIndex(cur_index).protoNode());
        if (!finfo.isValid() || finfo.headerInfo().id != hf_id) {
            // Did not find the selected hfid path in the selected packet
            cur_index = QModelIndex();
            emit fieldSelected(0);
            break;
        }
    }

    autoScrollTo(cur_index);
}

QString ProtoTree::traverseTree(const QModelIndex & travTree, int identLevel) const
{
    QString result = "";

    if ( travTree.isValid() )
    {
        result.append(QString("    ").repeated(identLevel));
        result.append(travTree.data().toString());
        result.append("\n");

        /* if the element is expanded, we traverse one level down */
        if ( isExpanded(travTree) )
        {
            int children = proto_tree_model_->rowCount(travTree);
            identLevel++;
            for ( int child = 0; child < children; child++ )
                result += traverseTree(proto_tree_model_->index(child, 0, travTree), identLevel);
        }
    }

    return result;
}

QString ProtoTree::toString(const QModelIndex &start_idx) const
{
    QString tree_string = "";
    if ( start_idx.isValid() )
        tree_string = traverseTree(start_idx, 0);
    else
    {
        int children = proto_tree_model_->rowCount();
        for ( int child = 0; child < children; child++ )
            tree_string += traverseTree(proto_tree_model_->index(child, 0, QModelIndex()), 0);
    }

    return tree_string;
}

void ProtoTree::setCaptureFile(capture_file *cf)
{
    // For use by the main view, set the capture file which will later have a
    // dissection (EDT) ready.
    // The packet dialog sets a fixed EDT context and MUST NOT use this.
    Q_ASSERT(edt_ == NULL);
    cap_file_ = cf;
}

bool ProtoTree::eventFilter(QObject * obj, QEvent * event)
{
    if ( event->type() != QEvent::MouseButtonPress && event->type() != QEvent::MouseMove )
        return QTreeView::eventFilter(obj, event);

    /* Mouse was over scrollbar, ignoring */
    if ( qobject_cast<QScrollBar *>(obj) )
        return QTreeView::eventFilter(obj, event);

    if ( event->type() == QEvent::MouseButtonPress )
    {
        QMouseEvent * ev = (QMouseEvent *)event;

        if ( ev->buttons() & Qt::LeftButton )
            drag_start_position_ = ev->pos();
    }
    else if ( event->type() == QEvent::MouseMove )
    {
        QMouseEvent * ev = (QMouseEvent *)event;

        if ( ( ev->buttons() & Qt::LeftButton ) && (ev->pos() - drag_start_position_).manhattanLength()
                 > QApplication::startDragDistance())
        {
            QModelIndex idx = indexAt(drag_start_position_);
            FieldInformation finfo(proto_tree_model_->protoNodeFromIndex(idx).protoNode());
            if ( finfo.isValid() )
            {
                /* Hack to prevent QItemSelection taking the item which has been dragged over at start
                 * of drag-drop operation. selectionModel()->blockSignals could have done the trick, but
                 * it does not take in a QTreeWidget (maybe View) */
                emit fieldSelected(&finfo);
                selectionModel()->select(idx, QItemSelectionModel::ClearAndSelect);

                epan_dissect_t *edt = cap_file_ ? cap_file_->edt : edt_;
                char *field_filter = proto_construct_match_selected_string(finfo.fieldInfo(), edt);
                QString filter(field_filter);
                wmem_free(NULL, field_filter);

                if ( filter.length() > 0 )
                {
                    DisplayFilterMimeData * dfmd =
                            new DisplayFilterMimeData(QString(finfo.headerInfo().name), QString(finfo.headerInfo().abbreviation), filter);
                    dfmd->setText(toString(idx));

                    QDrag * drag = new QDrag(this);
                    drag->setMimeData(dfmd);

                    DragLabel * content = new DragLabel(dfmd->labelText(), this);

                    qreal dpr = window()->windowHandle()->devicePixelRatio();
                    QPixmap pixmap(content->size() * dpr);
                    pixmap.setDevicePixelRatio(dpr);
                    content->render(&pixmap);
                    drag->setPixmap(pixmap);

                    drag->exec(Qt::CopyAction);

                    return true;
                }
            }
        }
    }

    return QTreeView::eventFilter(obj, event);
}

QModelIndex ProtoTree::moveCursor(QAbstractItemView::CursorAction cursorAction, Qt::KeyboardModifiers modifiers)
{
    if (cursorAction == MoveLeft && selectionModel()->hasSelection()) {
        QModelIndex cur_idx = selectionModel()->selectedIndexes().first();
        QModelIndex parent = cur_idx.parent();
        if (!isExpanded(cur_idx) && parent.isValid() && parent != rootIndex()) {
            return parent;
        }
    }
    return QTreeView::moveCursor(cursorAction, modifiers);
}

/*
 * Editor modelines
 *
 * Local Variables:
 * c-basic-offset: 4
 * tab-width: 8
 * indent-tabs-mode: nil
 * End:
 *
 * ex: set shiftwidth=4 tabstop=8 expandtab:
 * :indentSize=4:tabSize=8:noTabs=true:
 */