summaryrefslogtreecommitdiffstats
path: root/accessible/base/Logging.cpp
blob: 619af9e0a5d140c7dc41e6536f93049aa1fc4bc5 (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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "Logging.h"

#include "Accessible-inl.h"
#include "AccEvent.h"
#include "DocAccessible.h"
#include "DocAccessible-inl.h"
#include "nsAccessibilityService.h"
#include "nsCoreUtils.h"
#include "OuterDocAccessible.h"

#include "nsDocShellLoadTypes.h"
#include "nsIChannel.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsISelectionPrivate.h"
#include "nsTraceRefcnt.h"
#include "nsIWebProgress.h"
#include "prenv.h"
#include "nsIDocShellTreeItem.h"
#include "nsIURI.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/HTMLBodyElement.h"

using namespace mozilla;
using namespace mozilla::a11y;

////////////////////////////////////////////////////////////////////////////////
// Logging helpers

static uint32_t sModules = 0;

struct ModuleRep {
  const char* mStr;
  logging::EModules mModule;
};

static ModuleRep sModuleMap[] = {
  { "docload", logging::eDocLoad },
  { "doccreate", logging::eDocCreate },
  { "docdestroy", logging::eDocDestroy },
  { "doclifecycle", logging::eDocLifeCycle },

  { "events", logging::eEvents },
  { "eventTree", logging::eEventTree },
  { "platforms", logging::ePlatforms },
  { "text", logging::eText },
  { "tree", logging::eTree },

  { "DOMEvents", logging::eDOMEvents },
  { "focus", logging::eFocus },
  { "selection", logging::eSelection },
  { "notifications", logging::eNotifications },

  { "stack", logging::eStack },
  { "verbose", logging::eVerbose }
};

static void
EnableLogging(const char* aModulesStr)
{
  sModules = 0;
  if (!aModulesStr)
    return;

  const char* token = aModulesStr;
  while (*token != '\0') {
    size_t tokenLen = strcspn(token, ",");
    for (unsigned int idx = 0; idx < ArrayLength(sModuleMap); idx++) {
      if (strncmp(token, sModuleMap[idx].mStr, tokenLen) == 0) {
#if !defined(MOZ_PROFILING) && (!defined(DEBUG) || defined(MOZ_OPTIMIZE))
        // Stack tracing on profiling enabled or debug not optimized builds.
        if (strncmp(token, "stack", tokenLen) == 0)
          break;
#endif
        sModules |= sModuleMap[idx].mModule;
        printf("\n\nmodule enabled: %s\n", sModuleMap[idx].mStr);
        break;
      }
    }
    token += tokenLen;

    if (*token == ',')
      token++; // skip ',' char
  }
}

static void
LogDocURI(nsIDocument* aDocumentNode)
{
  printf("uri: %s", aDocumentNode->GetDocumentURI()->GetSpecOrDefault().get());
}

static void
LogDocShellState(nsIDocument* aDocumentNode)
{
  printf("docshell busy: ");

  nsAutoCString docShellBusy;
  nsCOMPtr<nsIDocShell> docShell = aDocumentNode->GetDocShell();
  uint32_t busyFlags = nsIDocShell::BUSY_FLAGS_NONE;
  docShell->GetBusyFlags(&busyFlags);
  if (busyFlags == nsIDocShell::BUSY_FLAGS_NONE) {
    printf("'none'");
  }
  if (busyFlags & nsIDocShell::BUSY_FLAGS_BUSY) {
    printf("'busy'");
  }
  if (busyFlags & nsIDocShell::BUSY_FLAGS_BEFORE_PAGE_LOAD) {
    printf(", 'before page load'");
  }
  if (busyFlags & nsIDocShell::BUSY_FLAGS_PAGE_LOADING) {
    printf(", 'page loading'");
  }
}

static void
LogDocType(nsIDocument* aDocumentNode)
{
  if (aDocumentNode->IsActive()) {
    bool isContent = nsCoreUtils::IsContentDocument(aDocumentNode);
    printf("%s document", (isContent ? "content" : "chrome"));
  } else {
    printf("document type: [failed]");\
  }
}

static void
LogDocShellTree(nsIDocument* aDocumentNode)
{
  if (aDocumentNode->IsActive()) {
    nsCOMPtr<nsIDocShellTreeItem> treeItem(aDocumentNode->GetDocShell());
    nsCOMPtr<nsIDocShellTreeItem> parentTreeItem;
    treeItem->GetParent(getter_AddRefs(parentTreeItem));
    nsCOMPtr<nsIDocShellTreeItem> rootTreeItem;
    treeItem->GetRootTreeItem(getter_AddRefs(rootTreeItem));
    printf("docshell hierarchy, parent: %p, root: %p, is tab document: %s;",
           static_cast<void*>(parentTreeItem), static_cast<void*>(rootTreeItem),
           (nsCoreUtils::IsTabDocument(aDocumentNode) ? "yes" : "no"));
  }
}

static void
LogDocState(nsIDocument* aDocumentNode)
{
  const char* docState = nullptr;
  nsIDocument::ReadyState docStateFlag = aDocumentNode->GetReadyStateEnum();
  switch (docStateFlag) {
    case nsIDocument::READYSTATE_UNINITIALIZED:
     docState = "uninitialized";
      break;
    case nsIDocument::READYSTATE_LOADING:
      docState = "loading";
      break;
    case nsIDocument::READYSTATE_INTERACTIVE:
      docState = "interactive";
      break;
    case nsIDocument::READYSTATE_COMPLETE:
      docState = "complete";
      break;
  }

  printf("doc state: %s", docState);
  printf(", %sinitial", aDocumentNode->IsInitialDocument() ? "" : "not ");
  printf(", %sshowing", aDocumentNode->IsShowing() ? "" : "not ");
  printf(", %svisible", aDocumentNode->IsVisible() ? "" : "not ");
  printf(", %svisible considering ancestors", aDocumentNode->IsVisibleConsideringAncestors() ? "" : "not ");
  printf(", %sactive", aDocumentNode->IsActive() ? "" : "not ");
  printf(", %sresource", aDocumentNode->IsResourceDoc() ? "" : "not ");

  dom::Element* rootEl = aDocumentNode->GetBodyElement();
  if (!rootEl) {
    rootEl = aDocumentNode->GetRootElement();
  }
  printf(", has %srole content", rootEl ? "" : "no ");
}

static void
LogPresShell(nsIDocument* aDocumentNode)
{
  nsIPresShell* ps = aDocumentNode->GetShell();
  printf("presshell: %p", static_cast<void*>(ps));

  nsIScrollableFrame* sf = nullptr;
  if (ps) {
    printf(", is %s destroying", (ps->IsDestroying() ? "" : "not"));
    sf = ps->GetRootScrollFrameAsScrollable();
  }
  printf(", root scroll frame: %p", static_cast<void*>(sf));
}

static void
LogDocLoadGroup(nsIDocument* aDocumentNode)
{
  nsCOMPtr<nsILoadGroup> loadGroup = aDocumentNode->GetDocumentLoadGroup();
  printf("load group: %p", static_cast<void*>(loadGroup));
}

static void
LogDocParent(nsIDocument* aDocumentNode)
{
  nsIDocument* parentDoc = aDocumentNode->GetParentDocument();
  printf("parent DOM document: %p", static_cast<void*>(parentDoc));
  if (parentDoc) {
    printf(", parent acc document: %p",
           static_cast<void*>(GetExistingDocAccessible(parentDoc)));
    printf("\n    parent ");
    LogDocURI(parentDoc);
    printf("\n");
  }
}

static void
LogDocInfo(nsIDocument* aDocumentNode, DocAccessible* aDocument)
{
  printf("    DOM document: %p, acc document: %p\n    ",
         static_cast<void*>(aDocumentNode), static_cast<void*>(aDocument));

  // log document info
  if (aDocumentNode) {
    LogDocURI(aDocumentNode);
    printf("\n    ");
    LogDocShellState(aDocumentNode);
    printf("; ");
    LogDocType(aDocumentNode);
    printf("\n    ");
    LogDocShellTree(aDocumentNode);
    printf("\n    ");
    LogDocState(aDocumentNode);
    printf("\n    ");
    LogPresShell(aDocumentNode);
    printf("\n    ");
    LogDocLoadGroup(aDocumentNode);
    printf(", ");
    LogDocParent(aDocumentNode);
    printf("\n");
  }
}

static void
LogShellLoadType(nsIDocShell* aDocShell)
{
  printf("load type: ");

  uint32_t loadType = 0;
  aDocShell->GetLoadType(&loadType);
  switch (loadType) {
    case LOAD_NORMAL:
      printf("normal; ");
      break;
    case LOAD_NORMAL_REPLACE:
      printf("normal replace; ");
      break;
    case LOAD_NORMAL_EXTERNAL:
      printf("normal external; ");
      break;
    case LOAD_HISTORY:
      printf("history; ");
      break;
    case LOAD_NORMAL_BYPASS_CACHE:
      printf("normal bypass cache; ");
      break;
    case LOAD_NORMAL_BYPASS_PROXY:
      printf("normal bypass proxy; ");
      break;
    case LOAD_NORMAL_BYPASS_PROXY_AND_CACHE:
      printf("normal bypass proxy and cache; ");
      break;
    case LOAD_NORMAL_ALLOW_MIXED_CONTENT:
      printf("normal allow mixed content; ");
      break;
    case LOAD_RELOAD_NORMAL:
      printf("reload normal; ");
      break;
    case LOAD_RELOAD_BYPASS_CACHE:
      printf("reload bypass cache; ");
      break;
    case LOAD_RELOAD_BYPASS_PROXY:
      printf("reload bypass proxy; ");
      break;
    case LOAD_RELOAD_BYPASS_PROXY_AND_CACHE:
      printf("reload bypass proxy and cache; ");
      break;
    case LOAD_RELOAD_ALLOW_MIXED_CONTENT:
      printf("reload allow mixed content; ");
      break;
    case LOAD_LINK:
      printf("link; ");
      break;
    case LOAD_REFRESH:
      printf("refresh; ");
      break;
    case LOAD_RELOAD_CHARSET_CHANGE:
      printf("reload charset change; ");
      break;
    case LOAD_BYPASS_HISTORY:
      printf("bypass history; ");
      break;
    case LOAD_STOP_CONTENT:
      printf("stop content; ");
      break;
    case LOAD_STOP_CONTENT_AND_REPLACE:
      printf("stop content and replace; ");
      break;
    case LOAD_PUSHSTATE:
      printf("load pushstate; ");
      break;
    case LOAD_REPLACE_BYPASS_CACHE:
      printf("replace bypass cache; ");
      break;
    case LOAD_ERROR_PAGE:
      printf("error page;");
      break;
    default:
      printf("unknown");
  }
}

static void
LogRequest(nsIRequest* aRequest)
{
  if (aRequest) {
    nsAutoCString name;
    aRequest->GetName(name);
    printf("    request spec: %s\n", name.get());
    uint32_t loadFlags = 0;
    aRequest->GetLoadFlags(&loadFlags);
    printf("    request load flags: %x; ", loadFlags);
    if (loadFlags & nsIChannel::LOAD_DOCUMENT_URI)
      printf("document uri; ");
    if (loadFlags & nsIChannel::LOAD_RETARGETED_DOCUMENT_URI)
      printf("retargeted document uri; ");
    if (loadFlags & nsIChannel::LOAD_REPLACE)
      printf("replace; ");
    if (loadFlags & nsIChannel::LOAD_INITIAL_DOCUMENT_URI)
      printf("initial document uri; ");
    if (loadFlags & nsIChannel::LOAD_TARGETED)
      printf("targeted; ");
    if (loadFlags & nsIChannel::LOAD_CALL_CONTENT_SNIFFERS)
      printf("call content sniffers; ");
    if (loadFlags & nsIChannel::LOAD_CLASSIFY_URI)
      printf("classify uri; ");
  } else {
    printf("    no request");
  }
}

static void
LogDocAccState(DocAccessible* aDocument)
{
  printf("document acc state: ");
  if (aDocument->HasLoadState(DocAccessible::eCompletelyLoaded))
    printf("completely loaded;");
  else if (aDocument->HasLoadState(DocAccessible::eReady))
    printf("ready;");
  else if (aDocument->HasLoadState(DocAccessible::eDOMLoaded))
    printf("DOM loaded;");
  else if (aDocument->HasLoadState(DocAccessible::eTreeConstructed))
    printf("tree constructed;");
}

static void
GetDocLoadEventType(AccEvent* aEvent, nsACString& aEventType)
{
  uint32_t type = aEvent->GetEventType();
  if (type == nsIAccessibleEvent::EVENT_DOCUMENT_LOAD_STOPPED) {
    aEventType.AssignLiteral("load stopped");
  } else if (type == nsIAccessibleEvent::EVENT_DOCUMENT_LOAD_COMPLETE) {
    aEventType.AssignLiteral("load complete");
  } else if (type == nsIAccessibleEvent::EVENT_DOCUMENT_RELOAD) {
    aEventType.AssignLiteral("reload");
  } else if (type == nsIAccessibleEvent::EVENT_STATE_CHANGE) {
    AccStateChangeEvent* event = downcast_accEvent(aEvent);
    if (event->GetState() == states::BUSY) {
      aEventType.AssignLiteral("busy ");
      if (event->IsStateEnabled())
        aEventType.AppendLiteral("true");
      else
        aEventType.AppendLiteral("false");
    }
  }
}

////////////////////////////////////////////////////////////////////////////////
// namespace logging:: document life cycle logging methods

static const char* sDocLoadTitle = "DOCLOAD";
static const char* sDocCreateTitle = "DOCCREATE";
static const char* sDocDestroyTitle = "DOCDESTROY";
static const char* sDocEventTitle = "DOCEVENT";
static const char* sFocusTitle = "FOCUS";

void
logging::DocLoad(const char* aMsg, nsIWebProgress* aWebProgress,
                 nsIRequest* aRequest, uint32_t aStateFlags)
{
  MsgBegin(sDocLoadTitle, aMsg);

  nsCOMPtr<mozIDOMWindowProxy> DOMWindow;
  aWebProgress->GetDOMWindow(getter_AddRefs(DOMWindow));
  nsPIDOMWindowOuter* window = nsPIDOMWindowOuter::From(DOMWindow);
  if (!window) {
    MsgEnd();
    return;
  }

  nsCOMPtr<nsIDocument> documentNode = window->GetDoc();
  if (!documentNode) {
    MsgEnd();
    return;
  }

  DocAccessible* document = GetExistingDocAccessible(documentNode);

  LogDocInfo(documentNode, document);

  nsCOMPtr<nsIDocShell> docShell = window->GetDocShell();
  printf("\n    ");
  LogShellLoadType(docShell);
  printf("\n");
  LogRequest(aRequest);
  printf("\n");
  printf("    state flags: %x", aStateFlags);
  bool isDocLoading;
  aWebProgress->GetIsLoadingDocument(&isDocLoading);
  printf(", document is %sloading\n", (isDocLoading ? "" : "not "));

  MsgEnd();
}

void
logging::DocLoad(const char* aMsg, nsIDocument* aDocumentNode)
{
  MsgBegin(sDocLoadTitle, aMsg);

  DocAccessible* document = GetExistingDocAccessible(aDocumentNode);
  LogDocInfo(aDocumentNode, document);

  MsgEnd();
}

void
logging::DocCompleteLoad(DocAccessible* aDocument, bool aIsLoadEventTarget)
{
  MsgBegin(sDocLoadTitle, "document loaded *completely*");

  printf("    DOM document: %p, acc document: %p\n",
         static_cast<void*>(aDocument->DocumentNode()),
         static_cast<void*>(aDocument));

  printf("    ");
  LogDocURI(aDocument->DocumentNode());
  printf("\n");

  printf("    ");
  LogDocAccState(aDocument);
  printf("\n");

  printf("    document is load event target: %s\n",
         (aIsLoadEventTarget ? "true" : "false"));

  MsgEnd();
}

void
logging::DocLoadEventFired(AccEvent* aEvent)
{
  nsAutoCString strEventType;
  GetDocLoadEventType(aEvent, strEventType);
  if (!strEventType.IsEmpty())
    printf("  fire: %s\n", strEventType.get());
}

void
logging::DocLoadEventHandled(AccEvent* aEvent)
{
  nsAutoCString strEventType;
  GetDocLoadEventType(aEvent, strEventType);
  if (strEventType.IsEmpty())
    return;

  MsgBegin(sDocEventTitle, "handled '%s' event", strEventType.get());

  DocAccessible* document = aEvent->GetAccessible()->AsDoc();
  if (document)
    LogDocInfo(document->DocumentNode(), document);

  MsgEnd();
}

void
logging::DocCreate(const char* aMsg, nsIDocument* aDocumentNode,
                   DocAccessible* aDocument)
{
  DocAccessible* document = aDocument ?
    aDocument : GetExistingDocAccessible(aDocumentNode);

  MsgBegin(sDocCreateTitle, aMsg);
  LogDocInfo(aDocumentNode, document);
  MsgEnd();
}

void
logging::DocDestroy(const char* aMsg, nsIDocument* aDocumentNode,
                    DocAccessible* aDocument)
{
  DocAccessible* document = aDocument ?
    aDocument : GetExistingDocAccessible(aDocumentNode);

  MsgBegin(sDocDestroyTitle, aMsg);
  LogDocInfo(aDocumentNode, document);
  MsgEnd();
}

void
logging::OuterDocDestroy(OuterDocAccessible* aOuterDoc)
{
  MsgBegin(sDocDestroyTitle, "outerdoc shutdown");
  logging::Address("outerdoc", aOuterDoc);
  MsgEnd();
}

void
logging::FocusNotificationTarget(const char* aMsg, const char* aTargetDescr,
                                 Accessible* aTarget)
{
  MsgBegin(sFocusTitle, aMsg);
  AccessibleNNode(aTargetDescr, aTarget);
  MsgEnd();
}

void
logging::FocusNotificationTarget(const char* aMsg, const char* aTargetDescr,
                                 nsINode* aTargetNode)
{
  MsgBegin(sFocusTitle, aMsg);
  Node(aTargetDescr, aTargetNode);
  MsgEnd();
}

void
logging::FocusNotificationTarget(const char* aMsg, const char* aTargetDescr,
                                 nsISupports* aTargetThing)
{
  MsgBegin(sFocusTitle, aMsg);

  if (aTargetThing) {
    nsCOMPtr<nsINode> targetNode(do_QueryInterface(aTargetThing));
    if (targetNode)
      AccessibleNNode(aTargetDescr, targetNode);
    else
      printf("    %s: %p, window\n", aTargetDescr,
             static_cast<void*>(aTargetThing));
  }

  MsgEnd();
}

void
logging::ActiveItemChangeCausedBy(const char* aCause, Accessible* aTarget)
{
  SubMsgBegin();
  printf("    Caused by: %s\n", aCause);
  AccessibleNNode("Item", aTarget);
  SubMsgEnd();
}

void
logging::ActiveWidget(Accessible* aWidget)
{
  SubMsgBegin();

  AccessibleNNode("Widget", aWidget);
  printf("    Widget is active: %s, has operable items: %s\n",
         (aWidget && aWidget->IsActiveWidget() ? "true" : "false"),
         (aWidget && aWidget->AreItemsOperable() ? "true" : "false"));

  SubMsgEnd();
}

void
logging::FocusDispatched(Accessible* aTarget)
{
  SubMsgBegin();
  AccessibleNNode("A11y target", aTarget);
  SubMsgEnd();
}

void
logging::SelChange(nsISelection* aSelection, DocAccessible* aDocument,
                   int16_t aReason)
{
  nsCOMPtr<nsISelectionPrivate> privSel(do_QueryInterface(aSelection));

  int16_t type = 0;
  privSel->GetType(&type);

  const char* strType = 0;
  if (type == nsISelectionController::SELECTION_NORMAL)
    strType = "normal";
  else if (type == nsISelectionController::SELECTION_SPELLCHECK)
    strType = "spellcheck";
  else
    strType = "unknown";

  bool isIgnored = !aDocument || !aDocument->IsContentLoaded();
  printf("\nSelection changed, selection type: %s, notification %s, reason: %d\n",
         strType, (isIgnored ? "ignored" : "pending"), aReason);

  Stack();
}

void
logging::TreeInfo(const char* aMsg, uint32_t aExtraFlags, ...)
{
  if (IsEnabledAll(logging::eTree | aExtraFlags)) {
    va_list vl;
    va_start(vl, aExtraFlags);
    const char* descr = va_arg(vl, const char*);
    if (descr) {
      Accessible* acc = va_arg(vl, Accessible*);
      MsgBegin("TREE", "%s; doc: %p", aMsg, acc ? acc->Document() : nullptr);
      AccessibleInfo(descr, acc);
      while ((descr = va_arg(vl, const char*))) {
        AccessibleInfo(descr, va_arg(vl, Accessible*));
      }
    }
    else {
      MsgBegin("TREE", aMsg);
    }
    va_end(vl);
    MsgEnd();

    if (aExtraFlags & eStack) {
      Stack();
    }
  }
}

void
logging::TreeInfo(const char* aMsg, uint32_t aExtraFlags,
                  const char* aMsg1, Accessible* aAcc,
                  const char* aMsg2, nsINode* aNode)
{
  if (IsEnabledAll(logging::eTree | aExtraFlags)) {
    MsgBegin("TREE", "%s; doc: %p", aMsg, aAcc ? aAcc->Document() : nullptr);
    AccessibleInfo(aMsg1, aAcc);
    Accessible* acc = aAcc ? aAcc->Document()->GetAccessible(aNode) : nullptr;
    if (acc) {
      AccessibleInfo(aMsg2, acc);
    }
    else {
      Node(aMsg2, aNode);
    }
    MsgEnd();
  }
}


void
logging::TreeInfo(const char* aMsg, uint32_t aExtraFlags, Accessible* aParent)
{
  if (IsEnabledAll(logging::eTree | aExtraFlags)) {
    MsgBegin("TREE", "%s; doc: %p", aMsg, aParent->Document());
    AccessibleInfo("container", aParent);
    for (uint32_t idx = 0; idx < aParent->ChildCount(); idx++) {
      AccessibleInfo("child", aParent->GetChildAt(idx));
    }
    MsgEnd();
  }
}

void
logging::Tree(const char* aTitle, const char* aMsgText,
              Accessible* aRoot, GetTreePrefix aPrefixFunc,
              void* aGetTreePrefixData)
{
  logging::MsgBegin(aTitle, aMsgText);

  nsAutoString level;
  Accessible* root = aRoot;
  do {
    const char* prefix = aPrefixFunc ? aPrefixFunc(aGetTreePrefixData, root) : "";
    printf("%s", NS_ConvertUTF16toUTF8(level).get());
    logging::AccessibleInfo(prefix, root);
    if (root->FirstChild() && !root->FirstChild()->IsDoc()) {
      level.Append(NS_LITERAL_STRING("  "));
      root = root->FirstChild();
      continue;
    }
    int32_t idxInParent = root != aRoot && root->mParent ?
      root->mParent->mChildren.IndexOf(root) : -1;
    if (idxInParent != -1 &&
        idxInParent < static_cast<int32_t>(root->mParent->mChildren.Length() - 1)) {
      root = root->mParent->mChildren.ElementAt(idxInParent + 1);
      continue;
    }
    while (root != aRoot && (root = root->Parent())) {
      level.Cut(0, 2);
      int32_t idxInParent = !root->IsDoc() && root->mParent ?
        root->mParent->mChildren.IndexOf(root) : -1;
      if (idxInParent != -1 &&
          idxInParent < static_cast<int32_t>(root->mParent->mChildren.Length() - 1)) {
        root = root->mParent->mChildren.ElementAt(idxInParent + 1);
        break;
      }
    }
  }
  while (root && root != aRoot);

  logging::MsgEnd();
}

void
logging::DOMTree(const char* aTitle, const char* aMsgText,
                 DocAccessible* aDocument)
{
  logging::MsgBegin(aTitle, aMsgText);
  nsAutoString level;
  nsINode* root = aDocument->DocumentNode();
  do {
    printf("%s", NS_ConvertUTF16toUTF8(level).get());
    logging::Node("", root);
    if (root->GetFirstChild()) {
      level.Append(NS_LITERAL_STRING("  "));
      root = root->GetFirstChild();
      continue;
    }
    if (root->GetNextSibling()) {
      root = root->GetNextSibling();
      continue;
    }
    while ((root = root->GetParentNode())) {
      level.Cut(0, 2);
      if (root->GetNextSibling()) {
        root = root->GetNextSibling();
        break;
      }
    }
  }
  while (root);
  logging::MsgEnd();
}

void
logging::MsgBegin(const char* aTitle, const char* aMsgText, ...)
{
  printf("\nA11Y %s: ", aTitle);

  va_list argptr;
  va_start(argptr, aMsgText);
  vprintf(aMsgText, argptr);
  va_end(argptr);

  PRIntervalTime time = PR_IntervalNow();
  uint32_t mins = (PR_IntervalToSeconds(time) / 60) % 60;
  uint32_t secs = PR_IntervalToSeconds(time) % 60;
  uint32_t msecs = PR_IntervalToMilliseconds(time) % 1000;
  printf("; %02d:%02d.%03d", mins, secs, msecs);

  printf("\n  {\n");
}

void
logging::MsgEnd()
{
  printf("  }\n");
}

void
logging::SubMsgBegin()
{
  printf("  {\n");
}

void
logging::SubMsgEnd()
{
  printf("  }\n");
}

void
logging::MsgEntry(const char* aEntryText, ...)
{
  printf("    ");

  va_list argptr;
  va_start(argptr, aEntryText);
  vprintf(aEntryText, argptr);
  va_end(argptr);

  printf("\n");
}

void
logging::Text(const char* aText)
{
  printf("  %s\n", aText);
}

void
logging::Address(const char* aDescr, Accessible* aAcc)
{
  if (!aAcc->IsDoc()) {
    printf("    %s accessible: %p, node: %p\n", aDescr,
           static_cast<void*>(aAcc), static_cast<void*>(aAcc->GetNode()));
  }

  DocAccessible* doc = aAcc->Document();
  nsIDocument* docNode = doc->DocumentNode();
  printf("    document: %p, node: %p\n",
         static_cast<void*>(doc), static_cast<void*>(docNode));

  printf("    ");
  LogDocURI(docNode);
  printf("\n");
}

void
logging::Node(const char* aDescr, nsINode* aNode)
{
  printf("    ");

  if (!aNode) {
    printf("%s: null\n", aDescr);
    return;
  }

  if (aNode->IsNodeOfType(nsINode::eDOCUMENT)) {
    printf("%s: %p, document\n", aDescr, static_cast<void*>(aNode));
    return;
  }

  nsINode* parentNode = aNode->GetParentNode();
  int32_t idxInParent = parentNode ? parentNode->IndexOf(aNode) : - 1;

  if (aNode->IsNodeOfType(nsINode::eTEXT)) {
    printf("%s: %p, text node, idx in parent: %d\n",
           aDescr, static_cast<void*>(aNode), idxInParent);
    return;
  }

  if (!aNode->IsElement()) {
    printf("%s: %p, not accessible node type, idx in parent: %d\n",
           aDescr, static_cast<void*>(aNode), idxInParent);
    return;
  }

  dom::Element* elm = aNode->AsElement();

  nsAutoCString tag;
  elm->NodeInfo()->NameAtom()->ToUTF8String(tag);

  nsIAtom* idAtom = elm->GetID();
  nsAutoCString id;
  if (idAtom)
    idAtom->ToUTF8String(id);

  printf("%s: %p, %s@id='%s', idx in parent: %d\n",
         aDescr, static_cast<void*>(elm), tag.get(), id.get(), idxInParent);
}

void
logging::Document(DocAccessible* aDocument)
{
  printf("    Document: %p, document node: %p\n",
         static_cast<void*>(aDocument),
         static_cast<void*>(aDocument->DocumentNode()));

  printf("    Document ");
  LogDocURI(aDocument->DocumentNode());
  printf("\n");
}

void
logging::AccessibleInfo(const char* aDescr, Accessible* aAccessible)
{
  printf("    %s: %p; ", aDescr, static_cast<void*>(aAccessible));
  if (!aAccessible) {
    printf("\n");
    return;
  }
  if (aAccessible->IsDefunct()) {
    printf("defunct\n");
    return;
  }
  if (!aAccessible->Document() || aAccessible->Document()->IsDefunct()) {
    printf("document is shutting down, no info\n");
    return;
  }

  nsAutoString role;
  GetAccService()->GetStringRole(aAccessible->Role(), role);
  printf("role: %s", NS_ConvertUTF16toUTF8(role).get());

  nsAutoString name;
  aAccessible->Name(name);
  if (!name.IsEmpty()) {
    printf(", name: '%s'", NS_ConvertUTF16toUTF8(name).get());
  }

  printf(", idx: %d", aAccessible->IndexInParent());

  nsINode* node = aAccessible->GetNode();
  if (!node) {
    printf(", node: null\n");
  }
  else if (node->IsNodeOfType(nsINode::eDOCUMENT)) {
    printf(", document node: %p\n", static_cast<void*>(node));
  }
  else if (node->IsNodeOfType(nsINode::eTEXT)) {
    printf(", text node: %p\n", static_cast<void*>(node));
  }
  else if (node->IsElement()) {
    dom::Element* el = node->AsElement();

    nsAutoCString tag;
    el->NodeInfo()->NameAtom()->ToUTF8String(tag);

    nsIAtom* idAtom = el->GetID();
    nsAutoCString id;
    if (idAtom) {
      idAtom->ToUTF8String(id);
    }

    printf(", element node: %p, %s@id='%s'\n",
           static_cast<void*>(el), tag.get(), id.get());
  }
}

void
logging::AccessibleNNode(const char* aDescr, Accessible* aAccessible)
{
  printf("    %s: %p; ", aDescr, static_cast<void*>(aAccessible));
  if (!aAccessible)
    return;

  nsAutoString role;
  GetAccService()->GetStringRole(aAccessible->Role(), role);
  nsAutoString name;
  aAccessible->Name(name);

  printf("role: %s, name: '%s';\n", NS_ConvertUTF16toUTF8(role).get(),
         NS_ConvertUTF16toUTF8(name).get());

  nsAutoCString nodeDescr(aDescr);
  nodeDescr.AppendLiteral(" node");
  Node(nodeDescr.get(), aAccessible->GetNode());

  Document(aAccessible->Document());
}

void
logging::AccessibleNNode(const char* aDescr, nsINode* aNode)
{
  DocAccessible* document =
    GetAccService()->GetDocAccessible(aNode->OwnerDoc());

  if (document) {
    Accessible* accessible = document->GetAccessible(aNode);
    if (accessible) {
      AccessibleNNode(aDescr, accessible);
      return;
    }
  }

  nsAutoCString nodeDescr("[not accessible] ");
  nodeDescr.Append(aDescr);
  Node(nodeDescr.get(), aNode);

  if (document) {
    Document(document);
    return;
  }

  printf("    [contained by not accessible document]:\n");
  LogDocInfo(aNode->OwnerDoc(), document);
  printf("\n");
}

void
logging::DOMEvent(const char* aDescr, nsINode* aOrigTarget,
                  const nsAString& aEventType)
{
  logging::MsgBegin("DOMEvents", "event '%s' %s",
                    NS_ConvertUTF16toUTF8(aEventType).get(), aDescr);
  logging::AccessibleNNode("Target", aOrigTarget);
  logging::MsgEnd();
}

void
logging::Stack()
{
  if (IsEnabled(eStack)) {
    printf("  stack: \n");
    nsTraceRefcnt::WalkTheStack(stdout);
  }
}

////////////////////////////////////////////////////////////////////////////////
// namespace logging:: initialization

bool
logging::IsEnabled(uint32_t aModules)
{
  return sModules & aModules;
}

bool
logging::IsEnabledAll(uint32_t aModules)
{
  return (sModules & aModules) == aModules;
}

bool
logging::IsEnabled(const nsAString& aModuleStr)
{
  for (unsigned int idx = 0; idx < ArrayLength(sModuleMap); idx++) {
    if (aModuleStr.EqualsASCII(sModuleMap[idx].mStr))
      return sModules & sModuleMap[idx].mModule;
  }

  return false;
}

void
logging::Enable(const nsAFlatCString& aModules)
{
  EnableLogging(aModules.get());
}


void
logging::CheckEnv()
{
  EnableLogging(PR_GetEnv("A11YLOG"));
}