forked from yuguorui/chrome-tabs-outliner-crack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
1888 lines (1885 loc) · 79.9 KB
/
background.js
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
// Input 0
/*
Copyright 2012, 2013, 2014, 2015 by Vladyslav Volovyk. All Rights Reserved. */
var debugLogChromeOperations = false;
if(localStorage["enableDetailedLogs"]) {
debugLogChromeOperations = true
}
function disableDetailedLogs() {
delete localStorage["enableDetailedLogs"];
debugLogChromeOperations = false
}
function enableDetailedLogs() {
localStorage["enableDetailedLogs"] = "true";
debugLogChromeOperations = true
}
try {
var CHROME_MAJOR_VERSION = parseInt(window.navigator.appVersion.match(/Chrome\/(\d+)\./)[1], 10)
}catch(e) {
console.error(e)
}
function getJsonFromQueryString(url) {
var questionMarkStart = url.indexOf("?");
var anchorStart = url.lastIndexOf("#");
var query = url.substring(questionMarkStart + 1, anchorStart < 0 ? url.length : anchorStart);
var data = query.split("&");
var result = {};
for(var i = 0;i < data.length;i++) {
var item = data[i].split("=");
result[item[0]] = item[1]
}
return result
}
function console_log_differenceTransaction(diff) {
console.group("Diff Data");
if(diff["k"]) {
for(var key in diff["k"]) {
console.log("%s:%c %s", key, "color:#522900", diff["k"][key])
}
}else {
console.log("NO KNOTS")
}
if(diff["c"]) {
for(key in diff["c"]) {
console.log("%s:%c %s", key, "color:#00297A", diff["c"][key])
}
}else {
console.log("NO ENTRIES")
}
for(key in diff) {
if(key != "k" && key != "c") {
console.log("%s:%c", key, "color:orange", diff[key])
}
}
console.groupEnd()
}
function getLocalStorageConfigInfoAsJsonString() {
var r = {};
for(var key in localStorage) {
if(localStorage.hasOwnProperty(key) && localStorage[key].length < 500) {
r[key] = localStorage[key]
}
}
return JSON.stringify(r)
}
var backEndInterface = new BackEndInterface;
function BackEndInterface() {
this.authorizedServerSides = ["http://localhost:8080", "https://tamnubatest.appspot.com", "https://gcdc2013-tabsoutliner.appspot.com", "https://tabs-outliner.appspot.com", "https://pro.tabsoutliner.com"];
this.profilePath = "/profile";
this.usedTokens = {}
}
BackEndInterface.prototype.ifThisIsOurServerSideProfilePathReturnParams = function(url) {
for(var i = 0;i < this.authorizedServerSides.length;i++) {
var testStr = this.authorizedServerSides[i] + this.profilePath;
if(url.indexOf(testStr) === 0) {
var r = getJsonFromQueryString(url.substr(testStr.length));
r.serverSideUri = this.authorizedServerSides[i];
return r
}
}
return null
};
BackEndInterface.prototype.titleContainConfirmIndicator = function(title) {
var confirmMark = "[#]";
return title.length - title.lastIndexOf(confirmMark) === confirmMark.length
};
BackEndInterface.prototype.callOnBackEndInterface = function(params_serverSideUri, actionToCall) {
var backEndInterfaceGlobalObjectCreatedByGatewayScript = "__backEndInterface";
if(!window[backEndInterfaceGlobalObjectCreatedByGatewayScript]) {
if(debugLogChromeOperations) {
console.log("BE-IS-NOT-READY-WILL-LOAD")
}
var backEndInterfaceScript = document.createElement("script");
backEndInterfaceScript.type = "text/javascript";
backEndInterfaceScript.async = true;
backEndInterfaceScript.src = params_serverSideUri + "/static/to_backend_gateway_4.js";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(backEndInterfaceScript, s);
backEndInterfaceScript.onload = function() {
actionToCall(window[backEndInterfaceGlobalObjectCreatedByGatewayScript])
};
backEndInterfaceScript.onerror = function() {
console.error("BEINT LOAD ERROR")
}
}else {
if(debugLogChromeOperations) {
console.log("BE-ALREADY-LOADED-AND-READY")
}
actionToCall(window[backEndInterfaceGlobalObjectCreatedByGatewayScript])
}
};
var lastSeenTabs = [];
function getNewChromeSessionAndUpdateChangedTabs() {
window.chrome.tabs.query({}, function(chromeActiveTabObjectsList) {
for(i = 0;i < chromeActiveTabObjectsList.length;i++) {
var isChanged = false;
var currentChromeTabObj = chromeActiveTabObjectsList[i];
var lastSeenChromeTabObj = lastSeenTabs[currentChromeTabObj.id];
if(lastSeenChromeTabObj && lastSeenChromeTabObj.title !== currentChromeTabObj.title) {
if(debugLogChromeOperations) {
console.log("TABSCHECKER New Tab Title:", lastSeenChromeTabObj.title, "--\x3e", currentChromeTabObj.title)
}
isChanged = true
}
if(lastSeenChromeTabObj && lastSeenChromeTabObj.url !== currentChromeTabObj.url) {
if(debugLogChromeOperations) {
console.log("TABSCHECKER New Tab Url:", lastSeenChromeTabObj.url, "--\x3e", currentChromeTabObj.url)
}
isChanged = true
}
if(lastSeenChromeTabObj && (currentChromeTabObj.favIconUrl && lastSeenChromeTabObj.favIconUrl !== currentChromeTabObj.favIconUrl)) {
if(debugLogChromeOperations) {
console.log("TABSCHECKER New Tab favIconUrl:", lastSeenChromeTabObj.favIconUrl, "--\x3e", currentChromeTabObj.favIconUrl)
}
isChanged = true
}
if(lastSeenChromeTabObj && lastSeenChromeTabObj.status !== currentChromeTabObj.status) {
if(debugLogChromeOperations) {
console.log("TABSCHECKER New Tab status:", lastSeenChromeTabObj.status, "--\x3e", currentChromeTabObj.status)
}
isChanged = true
}
if(isChanged) {
if(debugLogChromeOperations) {
console.log("TABSCHECKER DETECT TAB UPDATE", currentChromeTabObj)
}
if(activeSession && activeSession.treeModel) {
var tabModel = activeSession.treeModel.findActiveTab(currentChromeTabObj.id);
if(tabModel) {
tabModel.updateChromeTabObj(currentChromeTabObj)
}
}
}
}
lastSeenTabs = [];
for(var i = 0;i < chromeActiveTabObjectsList.length;i++) {
lastSeenTabs[chromeActiveTabObjectsList[i].id] = chromeActiveTabObjectsList[i]
}
})
}
function checkTabsChanges() {
var CHECK_INTERVAL = 2E3;
if(debugLogChromeOperations) {
console.log("@@@@@ TABS CHECK STARTED, interval:", CHECK_INTERVAL)
}
function tabsCheck() {
getNewChromeSessionAndUpdateChangedTabs();
setTimeout(tabsCheck, CHECK_INTERVAL)
}
tabsCheck()
}
checkTabsChanges();
function threadCheck() {
var CHECK_INTERVAL = 30;
console.log("@@@@@ THREAD CHECK STARTED, interval:", CHECK_INTERVAL);
var startTime = Date.now();
var lastCheckTime = startTime;
var checks = [];
function threadCheckCheck() {
var time = Date.now();
checks.push(time - lastCheckTime <= CHECK_INTERVAL + 7 ? "." : time - lastCheckTime);
if(time - startTime < 1E4) {
setTimeout(threadCheckCheck, CHECK_INTERVAL)
}else {
var msg = "";
for(var i = 0;i < checks.length;i++) {
msg += checks[i] + " "
}
console.log("@@@@@ THREAD CHECKS:\n", msg)
}
lastCheckTime = time
}
threadCheckCheck()
}
function serializeActiveSessionToJSO() {
return activeSession.treeModel.serializeHierarchyAsJSO()
}
function serializeActiveSessionToOperations() {
return activeSession.treeModel.serializeAsOperationsLog()
}
function saveCurrentSessionAsJSONtoLocalStorage() {
console.log("saveCurrentSessionAsJSON to LocalStorage ====================================");
var startTime = Date.now();
var dataToSave_Objects_startTime = Date.now();
var dataToSave_Objects = serializeActiveSessionToJSO();
var dataToSave_Objects_stopTime = Date.now();
var dataToSave_Strings_startTime = Date.now();
var dataToSave_Strings = JSON.stringify(dataToSave_Objects);
var dataToSave_Strings_stopTime = Date.now();
var startToStorageTime = Date.now();
localStorage.setItem(currentSessionSnapshotDbKey, dataToSave_Strings);
localStorage.setItem("timestamp", Date.now());
var stopToStorageTime = Date.now();
console.log("SerializeToObjectsTime", dataToSave_Objects_stopTime - dataToSave_Objects_startTime);
console.log("ObjectsToStringTime", dataToSave_Strings_stopTime - dataToSave_Strings_startTime);
console.log("SaveTime", stopToStorageTime - startToStorageTime);
console.log("FullSaveTime", stopToStorageTime - startTime);
console.log("")
}
function saveCurrentSessionAsOperationsToIndexedDbNow() {
var startTime = Date.now();
var dataToSave_Objects = serializeActiveSessionToOperations();
var startToStorageTime = Date.now();
saveToDefaultIndexedDB(currentSessionSnapshotDbKey, dataToSave_Objects);
var stopToStorageTime = Date.now()
}
if(!window.indexedDB) {
var indexedDB = window.indexedDB || (window.webkitIndexedDB || (window.mozIndexedDB || window.msIndexedDB))
}
if(!window.IDBTransaction) {
var IDBTransaction = window.IDBTransaction || (window.webkitIDBTransaction || (window.mozIDBTransaction || window.msIDBTransaction))
}
var INDEXED_DB_TRANSACTION_readonly = CHROME_MAJOR_VERSION < 22 ? IDBTransaction.READ_ONLY : "readonly";
var INDEXED_DB_TRANSACTION_readwrite = CHROME_MAJOR_VERSION < 22 ? IDBTransaction.READ_WRITE : "readwrite";
var dataBaseSchemeV33 = {dbName:"TabsOutlinerDB2", dbVersion:2, dbObjectStoreName:"current_session_snapshot"};
var dataBaseSchemeV34_Default = {dbName:"TabsOutlinerDB34", dbVersion:2, dbObjectStoreName:"current_session_snapshot"};
var currentSessionSnapshotDbKey = "currentSessionSnapshot";
function openIndexedDbToUse_neverCreateAnything(dataBaseScheme, useDbCallback) {
throw new Error;var openRequest = indexedDB.open(dataBaseScheme.dbName, dataBaseScheme.dbVersion);
openRequest.onblocked = function(event) {
if(console) {
console.error("ERROR IndexedDB openRequest.onblocked", event)
}
useDbCallback(null)
};
openRequest.onerror = function(event) {
if(console) {
console.error("ERROR IndexedDB openRequest.onerror", event.target.webkitErrorMessage, event.target.errorCode, event)
}
useDbCallback(null)
};
openRequest.onsuccess = function(event) {
var db = this.result;
useDbCallback(db)
}
}
function openIndexedDbToUse_createStoreIfAbsent(dataBaseScheme, useDbCallback) {
var startTime_openIndexedDbToUse = Date.now();
var openRequest = indexedDB.open(dataBaseScheme.dbName, dataBaseScheme.dbVersion);
openRequest.onblocked = function(event) {
if(console) {
console.error("ERROR IndexedDB openRequest.onblocked:", event)
}
useDbCallback(null)
};
openRequest.onerror = function(event) {
if(console) {
console.error("ERROR IndexedDB openRequest.onerror:", event["target"]["webkitErrorMessage"], event["target"]["errorCode"], event, "\nSERIOUS ERROR IndexedDB folder is corrupted most likely - need manualy delete the extension IndexedDB folder to recover from this!\n" + "the folder is contained in Chrome profile (use chrome:version to learn the correct path) and has the name: \nIndexedDB/chrome-extension_eggkanocgddhmamlbiijnphhppkpkmkl_0.indexeddb.leveldb\n" + "This was very common error in Chrome v24 and Chrome v25 because of some LevelDB engine bug which was introduced in Chrome v24; \nChrome v26 delete such corrupted database folders on open automaticaly")
}
useDbCallback(null)
};
openRequest.onupgradeneeded = function(event) {
if(console) {
console.log("IndexedDB openRequest.onupgradeneeded", event)
}
var db = event.target.result;
createObjectStoreAndIndexIfNoObjectStores(db, dataBaseScheme, event.oldVersion)
};
openRequest.onsuccess = function(event) {
var db = this.result;
var oldVersion = Number(db.version);
if(oldVersion !== dataBaseScheme.dbVersion) {
if(console) {
console.log("IndexedDB openRequest.onsuccess - oldVersion !== dbVersion - will do db.setVersion", event)
}
if(!db.setVersion) {
throw new Error;
}
var versionRequest = db.setVersion(dataBaseScheme.dbVersion);
versionRequest.onsuccess = function(event) {
if(console) {
console.log("IndexedDB versionRequest.onsuccess", event)
}
createObjectStoreAndIndexIfNoObjectStores(db, dataBaseScheme, oldVersion);
var transaction = event.target.result;
transaction.oncomplete = function() {
useDbCallback(db)
}
}
}else {
useDbCallback(db)
}
}
}
function createObjectStoreAndIndexIfNoObjectStores(db, dataBaseScheme, oldVersion) {
if(console) {
console.log("IndexedDB = Create ObjectStore in DB ===================")
}
if(db["objectStoreNames"].length === 0) {
var objectStore = db.createObjectStore(dataBaseScheme.dbObjectStoreName, {"keyPath":"key"});
objectStore.createIndex("key", "key", {"unique":true})
}
}
function saveDataToDB(db, objectStoreName, key, JSO, onDone) {
var transaction = db.transaction([objectStoreName], INDEXED_DB_TRANSACTION_readwrite);
var objectStore = transaction.objectStore(objectStoreName);
var startRIB_add = Date.now();
var data = {"key":key, "data":JSO};
var putRequest = objectStore.put(data);
var stopRIB_add = Date.now();
putRequest.onsuccess = function(event) {
};
putRequest.onerror = function(event) {
if(console) {
console.log("IndexedDB ERROR putRequest.onerror", event)
}
};
transaction.oncomplete = function(event) {
if(onDone) {
onDone(db)
}
};
transaction.onerror = function(event) {
if(console) {
console.log("IndexedDB ERROR write transaction.onerror", event)
}
}
}
function readDataFromDB(db, objectStoreName, key, callback) {
var transaction = db.transaction([objectStoreName], INDEXED_DB_TRANSACTION_readonly);
var getRequest = transaction.objectStore(objectStoreName).get(key);
getRequest.onsuccess = function(event) {
if(event.target.result === undefined) {
callback(undefined)
}else {
callback(event.target.result.data)
}
};
getRequest.onerror = function(event) {
if(console) {
console.log("IndexedDB ERROR getRequest.onerror", event)
}
callback(undefined)
};
transaction.oncomplete = function(event) {
};
transaction.onerror = function(event) {
if(console) {
console.log("IndexedDB ERROR read transaction.onerror", event)
}
callback(undefined)
}
}
function saveToDefaultIndexedDB(key, data) {
if(debugLogChromeOperations) {
if(console) {
console.log("saveToDefaultIndexedDB START", (new Date).toTimeString())
}
}
openIndexedDbToUse_createStoreIfAbsent(dataBaseSchemeV34_Default, function(db) {
if(db) {
saveDataToDB(db, dataBaseSchemeV34_Default.dbObjectStoreName, key, data, function() {
})
}else {
window["treeWriteFail"] = true
}
})
}
function readOperationsFromIndexedDB(dataBaseScheme, callback) {
var multipleCallbackinvocationOnErrorsChecker_db = 0;
if(++multipleCallbackinvocationOnErrorsChecker_db !== 1) {
return
}
openIndexedDbToUse_createStoreIfAbsent(dataBaseScheme, function(db) {
try {
if(!db) {
throw new Error("IDB open error");
}
readDataFromDB(db, dataBaseScheme.dbObjectStoreName, currentSessionSnapshotDbKey, function(data) {
if(console) {
console.log("IDB READ-DONE", dataBaseScheme.dbName)
}
try {
callback(data)
}catch(e) {
console.error("ERROR !!! IDB READ CALLBACK EXECUTION EXCEPTION - ERROR DURING TREE INSTANTIATION FROM SERIALIZED DATA", e);
console.log(e["message"]);
console.log(e["stack"])
}
})
}catch(e) {
console.error("ERROR !!! IDB READ ERROR", dataBaseScheme.dbName, e);
console.log(e["message"]);
console.log(e["stack"]);
callback(null)
}
})
}
var OnRemovedTracker = Class.extend({init:function() {
this.PERIOD_OF_INACTIVITY_BEFORE_CLEARING_DATA = 25 * 1E3;
this.lastSessionOnRemoved = this._getDataFromLocalStorage();
this.clearStorage()
}, clearStorage:function() {
this.recentlyRemoved = this.getEmptyOnRemovedCollection();
this._dumpDataToLocalStorage();
this.clearTimerID = null
}, getEmptyOnRemovedCollection:function() {
return{"removedTabs":{}, "removedWindows":{}}
}, _dumpDataToLocalStorage:function() {
try {
var s = JSON.stringify(this.recentlyRemoved);
if(s.length < 1E5) {
localStorage["recentlyRemoved"] = s
}
}catch(e) {
console.error("ERROR DDTLS", e)
}
}, _getDataFromLocalStorage:function() {
try {
var removedItems = JSON.parse(localStorage["recentlyRemoved"])
}catch(e) {
}
if(!removedItems || (!removedItems["removedWindows"] || !removedItems["removedTabs"])) {
removedItems = this.getEmptyOnRemovedCollection()
}
return removedItems
}, recentlyRemovedItemsListUpdated_dubpData_scheduleClear:function() {
this._dumpDataToLocalStorage();
window.clearTimeout(this.clearTimerID);
this.clearTimerID = window.setTimeout(this.clearStorage.bind(this), this.PERIOD_OF_INACTIVITY_BEFORE_CLEARING_DATA)
}, register_onTabRemoved:function(tabId, isWindowClosingInfo) {
this.recentlyRemoved["removedTabs"][tabId] = isWindowClosingInfo;
if(isWindowClosingInfo && isWindowClosingInfo.isWindowClosing) {
this.recentlyRemoved["removedWindows"][isWindowClosingInfo.windowId] = Date.now()
}
this.recentlyRemovedItemsListUpdated_dubpData_scheduleClear()
}, register_onWindowRemoved:function(windowId) {
this.recentlyRemoved["removedWindows"][windowId] = Date.now();
this.recentlyRemovedItemsListUpdated_dubpData_scheduleClear()
}, getTabsOnRemovedEventsFromLastSession:function() {
return this.lastSessionOnRemoved["removedTabs"]
}, getWindowsOnRemovedEventsFromLastSession:function() {
return this.lastSessionOnRemoved["removedWindows"]
}, EOC:null});
function SaveScheduler(saveFunction, UPDATES_ACCUMULATING_PERIOD, MAXIMUM_POSTPONE_BECAUSE_OF_UPDATES_PERIOD_BEFORE_FORCED_SAVE) {
this.performSaveFunction = saveFunction;
this.timeOfFirstUnsavedUpdate = null;
this.timeoutCallId = 0;
this.MAXIMUM_POSTPONE_BECAUSE_OF_UPDATES_PERIOD_BEFORE_FORCED_SAVE = MAXIMUM_POSTPONE_BECAUSE_OF_UPDATES_PERIOD_BEFORE_FORCED_SAVE;
this.UPDATES_ACCUMULATING_PERIOD = UPDATES_ACCUMULATING_PERIOD
}
SaveScheduler.prototype = {_cancellAnyAlreadyScheduledSaveCall:function() {
window.clearTimeout(this.timeoutCallId)
}, _callSave:function() {
if(debugLogChromeOperations) {
console.log("SaveScheduler(%d)::_callSave():", this.UPDATES_ACCUMULATING_PERIOD)
}
this.timeOfFirstUnsavedUpdate = null;
this.performSaveFunction()
}, _scheduleSaveCall:function(period) {
this.timeoutCallId = window.setTimeout(this._callSave.bind(this), period)
}, _isWeAllreadyPostponeSaveExecutionForTooMuch:function() {
return Date.now() - this.timeOfFirstUnsavedUpdate > this.MAXIMUM_POSTPONE_BECAUSE_OF_UPDATES_PERIOD_BEFORE_FORCED_SAVE
}, processUpdateRequest:function() {
if(!this.timeOfFirstUnsavedUpdate) {
this.timeOfFirstUnsavedUpdate = Date.now()
}
var scheduleToCallInNmilisecond = this._isWeAllreadyPostponeSaveExecutionForTooMuch() ? 1 : this.UPDATES_ACCUMULATING_PERIOD;
if(debugLogChromeOperations) {
console.log("SaveScheduler(%d)::processUpdateRequest scheduleToCallInNmilisecond:", this.UPDATES_ACCUMULATING_PERIOD, scheduleToCallInNmilisecond)
}
this._cancellAnyAlreadyScheduledSaveCall();
this._scheduleSaveCall(scheduleToCallInNmilisecond)
}};
var TreeModelPersistenceManagerAbstractBase = Class.extend({init:function() {
this.tree = null;
this.localStorageQuataReached = false;
this.fullSaveScheduler = new SaveScheduler(this._diff_and_full_performScheduledSave.bind(this), 3E3, 8 * 1E3)
}, registerTree:function(tree) {
this.tree = tree
}, restoreTree:function(callback) {
}, saveTree:function(isPerformSureSynchronousSave_onViewClose) {
}, diff_saveTree:function() {
}, saveNow:function() {
if(this.fullSaveScheduler.timeOfFirstUnsavedUpdate == null) {
return
}
this.fullSaveScheduler._cancellAnyAlreadyScheduledSaveCall();
this._diff_and_full_performScheduledSave(true);
this.fullSaveScheduler.timeOfFirstUnsavedUpdate = null
}, _diff_and_full_performScheduledSave:function(doLocalStorageSave) {
try {
this.diff_saveTree()
}catch(e) {
console.error("!!! diff_saveTree exception:", e)
}
try {
this.saveTree(!!doLocalStorageSave)
}catch(e) {
console.error("!!! saveTree exception:", e)
}
}, _diff_performScheduledSave:function() {
try {
this.diff_saveTree()
}catch(e) {
console.error("!!! diff_saveTree3 exception:", e)
}
}, treeUpdated:function() {
this.fullSaveScheduler.processUpdateRequest()
}, EOC:null});
var TreeModelPersistenceManagerIndexedDB = TreeModelPersistenceManagerAbstractBase.extend({restoreTree:function(callback) {
readOperationsFromIndexedDB(dataBaseSchemeV34_Default, function(savedOperations) {
callback(savedOperations ? restoreTreeFromOperations(savedOperations) : null)
})
}, saveTree:function() {
saveCurrentSessionAsOperationsToIndexedDbNow()
}, EOC:null});
var TreeModelPersistenceManagerLocalStorage = TreeModelPersistenceManagerAbstractBase.extend({restoreTree:function(callback) {
var savedData = JSON.parse(localStorage.getItem(currentSessionSnapshotDbKey));
callback(savedData && savedData["node"] ? restoreHierarchyFromJSO(savedData) : null)
}, saveTree:function() {
saveCurrentSessionAsJSONtoLocalStorage()
}, EOC:null});
var TreeModelPersistenceManagerIndexedDBAndFilesystem = TreeModelPersistenceManagerAbstractBase.extend({restoreTree:function(callback___________) {
setTimeout(consoleLoglistOfAllFiles, 1);
var serviceOptions_restoreSource = localStorage["serviceOptions_restoreSource"];
delete localStorage["serviceOptions_restoreSource"];
switch(serviceOptions_restoreSource) {
case "indexedDB":
readOperationsFromIndexedDB(dataBaseSchemeV34_Default, function(indexedDbSavedOperations_v34) {
if(isValidV34Data_endNodeIsEof(indexedDbSavedOperations_v34)) {
callback___________(restoreTreeFromOperations(indexedDbSavedOperations_v34))
}
});
return;
case "file":
readSessionDataFromFile(currentSessionSnapshotFilename, function(fileSavedOperations) {
if(isValidV34Data_endNodeIsEof(fileSavedOperations)) {
callback___________(restoreTreeFromOperations(fileSavedOperations))
}
});
return;
case "webSQL":
readSessionDataBackupFromWebSQL(function(webSqlSavedOperations) {
if(isValidV34Data_endNodeIsEof(webSqlSavedOperations)) {
callback___________(restoreTreeFromOperations(webSqlSavedOperations))
}
});
return;
case "localstorage":
var treeInLocalStorage = JSON.parse(localStorage["onViewClose_lastSessionSnapshot"]);
if(isValidV34Data_endNodeIsEof(treeInLocalStorage)) {
callback___________(restoreTreeFromOperations(treeInLocalStorage))
}
return;
default:
readSessionDataFromFile(serviceOptions_restoreSource, function(fileSavedOperations) {
if(isValidV34Data_endNodeIsEof(fileSavedOperations)) {
callback___________(restoreTreeFromOperations(fileSavedOperations))
}
});
return;
case undefined:
}
readOperationsFromIndexedDB(dataBaseSchemeV34_Default, function(indexedDbSavedOperations_v34) {
if(getV34DataSaveTime(indexedDbSavedOperations_v34) == localStorage["lastSessionSnapshotSaveTime"]) {
if(console) {
console.log("DB read ok; Data in DB have known lastSessionSnapshotSaveTime")
}
callback___________(restoreTreeFromOperations(indexedDbSavedOperations_v34))
}else {
if(console) {
console.log("No valid v34 data in database, or with unknown lastSaveTime (V34DataSaveTime, localStorage.lastSessionSnapshotSaveTime):", getV34DataSaveTime(indexedDbSavedOperations_v34), localStorage["lastSessionSnapshotSaveTime"])
}
var multipleCallbackinvocationOnErrorsChecker_file = 0;
readSessionDataFromFile(currentSessionSnapshotFilename, function(fileSavedOperations) {
if(++multipleCallbackinvocationOnErrorsChecker_file !== 1) {
return
}
try {
var localStorageSavedOperations = JSON.parse(localStorage["onViewClose_lastSessionSnapshot"])
}catch(e) {
}
var idb_tstmp = getV34DataSaveTime(indexedDbSavedOperations_v34);
var file_tstmp = getV34DataSaveTime(fileSavedOperations);
var lstr_tstmp = getV34DataSaveTime(localStorageSavedOperations);
console.log("IDB, file, localstorage snapshots timestamps & lastSessionSnapshotSaveTime:", idb_tstmp, file_tstmp, lstr_tstmp, localStorage["lastSessionSnapshotSaveTime"]);
if(file_tstmp == localStorage["lastSessionSnapshotSaveTime"]) {
if(console) {
console.log("Data in file have known lastSaveTime, will restore tree from file")
}
callback___________(restoreTreeFromOperations(fileSavedOperations))
}else {
if(lstr_tstmp == localStorage["lastSessionSnapshotSaveTime"]) {
if(console) {
console.log("Data in localStorage have known lastSaveTime, will restore tree from localStorage")
}
callback___________(restoreTreeFromOperations(localStorageSavedOperations))
}else {
if(console) {
console.log("Nor file, nor idb, nor localstorage have data with lastSessionSnapshotSaveTime", localStorage["lastSessionSnapshotSaveTime"])
}
if(idb_tstmp || file_tstmp) {
var freshestData = [[idb_tstmp || 0, indexedDbSavedOperations_v34], [file_tstmp || 0, fileSavedOperations], [lstr_tstmp || 0, localStorageSavedOperations]];
freshestData.sort(function(a, b) {
return b[0] - a[0]
});
if(console) {
console.log("No data with known save time, will restore the freshest store")
}
callback___________(restoreTreeFromOperations(freshestData[0][1]))
}else {
if(console) {
console.log("No valid DB34 nor File nor localStorage with knownSaveTime data")
}
if(localStorage["lastSessionSnapshotSaveTime"]) {
if(console) {
console.log("localStorage.lastSessionSnapshotSaveTime is present, so it's not fresh install, will try to read WebSQL backup", localStorage["lastSessionSnapshotSaveTime"])
}
readSessionDataBackupFromWebSQL(function(webSqlSavedOperations) {
if(isValidV34Data_endNodeIsEof(webSqlSavedOperations)) {
if(console) {
console.log("WebSQL READ OK")
}
callback___________(restoreTreeFromOperations(webSqlSavedOperations))
}else {
if(console) {
console.log("WebSQL return non valid data. Will stop now to not overwrite the data by empty tree. Contact the author please: [email protected]")
}
}
})
}else {
readOperationsFromIndexedDB(dataBaseSchemeV33, function(indexedDbSavedOperations_v33_old) {
if(indexedDbSavedOperations_v33_old) {
if(console) {
console.log("TABSOUTLINER UPGRADE")
}
localStorage["v34upgrade"] = Date.now();
callback___________(restoreTreeFromOperations(indexedDbSavedOperations_v33_old))
}else {
if(console) {
console.log("TABSOUTLINER FRESH INSTALL")
}
localStorage["install"] = Date.now();
localStorage["relateNewTabToOpener"] = "true";
callback___________(restoreTreeFromOperations([]));
ga_setInstanceInstallTimeDimensions()
}
})
}
}
}
}
})
}
})
}, registerTree:function(tree) {
this._super(tree)
}, diff_saveTree:function() {
}, saveTree:function(isSynchronousUnscheduledSaveRequested) {
var sessionDataAsOperations = this.tree.serializeAsOperationsLog();
localStorage["lastSessionSnapshotSaveTime"] = sessionDataAsOperations[sessionDataAsOperations.length - 1]["time"];
localStorage["lastSavedSessionSnapshotLength"] = sessionDataAsOperations.length;
var webSqlBackupPeriod = 20 * 60 * 1E3;
var isTimeForWebSqlBackup = !window["lastWebSqlBackupTime"] || window["lastWebSqlBackupTime"] + webSqlBackupPeriod < Date.now();
try {
if(!this.localStorageQuataReached && (isSynchronousUnscheduledSaveRequested || isTimeForWebSqlBackup)) {
var exportDataString = JSON.stringify(sessionDataAsOperations);
if(exportDataString.length < 2333444) {
try {
localStorage["onViewClose_lastSessionSnapshot"] = exportDataString
}catch(e) {
window.chrome.extension.getBackgroundPage().console.error("ERROR SSC QUATA", e)
}
}else {
window.chrome.extension.getBackgroundPage().console.warn("WARNING SSC QUATA");
this.localStorageQuataReached = true
}
}
}catch(e) {
}
setTimeout(function() {
saveToDefaultIndexedDB(currentSessionSnapshotDbKey, sessionDataAsOperations)
}, 1);
setTimeout(function() {
saveSessionDataAsFile(currentSessionSnapshotFilename, sessionDataAsOperations)
}, 1);
if(window["treeWriteFail"] || isTimeForWebSqlBackup) {
setTimeout(function() {
backupSessionDataInWebSQL(JSON.stringify(sessionDataAsOperations), sessionDataAsOperations.length)
}, 1);
window["lastWebSqlBackupTime"] = Date.now()
}
performBackups(sessionDataAsOperations, "lastDaylyBackupTime", 24 * 60 * 60 * 1E3, "d-backup-", 9);
performBackups(sessionDataAsOperations, "lastHourlyBackupTime", 60 * 60 * 1E3, "h-backup-", 6)
}, EOC:null});
function backupSessionDataInWebSQL(dataString, op_array_len) {
var db = openDatabase("backupdb", "1.0", "Tree Backup", 20 * 1024 * 1024);
db.transaction(function(tx) {
tx.executeSql("CREATE TABLE IF NOT EXISTS current_session_snapshot (id unique, timestamp, op_array_len, data)");
tx.executeSql("INSERT OR REPLACE INTO current_session_snapshot (id, timestamp, op_array_len, data) VALUES (?, ?, ?, ?)", [1, Date.now(), op_array_len, dataString])
})
}
function readSessionDataBackupFromWebSQL(callback) {
var db = openDatabase("backupdb", "1.0", "Tree Backup", 20 * 1024 * 1024);
db.readTransaction(function(tx) {
tx.executeSql("SELECT * FROM current_session_snapshot WHERE id == 1", [], function(tx, results) {
var result = results.rows.item(0);
if(!result) {
if(console) {
console.log("WEBSQL backup read error - result is empty")
}
callback(null)
}else {
try {
var operations = JSON.parse(result.data)
}catch(parseError) {
callback(parseError)
}
callback(operations)
}
}, function(error) {
if(console) {
console.log("WEBSQL executeSql error:", error)
}
callback(null)
})
})
}
function getV34DataSaveTime(operations) {
if(isValidV34Data_endNodeIsEof(operations)) {
return operations[operations.length - 1]["time"]
}
return NaN
}
function isValidV34Data_endNodeIsEof(operations) {
return operations && (operations.length && (operations.length >= 2 && (operations[0]["type"] == DbOperations.OperationsEnum.NODE_NEWROOT && operations[operations.length - 1]["type"] == DbOperations.OperationsEnum.EOF)))
}
function performBackups(sessionDataAsOperations, localStorageFieldForLastBackupTimestamp, timeBetweenBackups, backupFilePrefix, howManyBackupsHandle) {
var lastBackupTime = Number(localStorage[localStorageFieldForLastBackupTimestamp] || 0);
if(Math.abs(Date.now() - lastBackupTime) > timeBetweenBackups) {
localStorage[localStorageFieldForLastBackupTimestamp] = Date.now();
setTimeout(function() {
saveSessionDataAsFile(backupFilePrefix + Date.now() + "-" + sessionDataAsOperations.length + ".json", sessionDataAsOperations, function onwriteend() {
deleteOlderBackups(backupFilePrefix, howManyBackupsHandle)
})
}, 5E3 + Math.round(Math.random() * 2E3))
}
}
function deleteOlderBackups(backupFilePrefix, howManyBackupsHandle) {
listAllFiles(function(entries) {
var pattern = new RegExp(backupFilePrefix + "([\\d]*)-[\\d]*\\.json");
var nowTime = Date.now();
var sortedBackupFilesWithTime = entries.filter(function(dirEntry) {
return dirEntry.isFile && pattern.test(dirEntry.name)
}).map(function(dirEntry) {
return{"dirEntry":dirEntry, "time":Number(dirEntry.name.match(pattern)[1])}
}).sort(function(o1, o2) {
return Math.abs(o1["time"] - nowTime) - Math.abs(o2["time"] - nowTime)
});
for(var i = howManyBackupsHandle;i < sortedBackupFilesWithTime.length;i++) {
deleteFileByFullPath(sortedBackupFilesWithTime[i]["dirEntry"].fullPath)
}
})
}
function deleteFileByFullPath(fullPath, continuneCallback) {
continuneCallback = continuneCallback || function() {
};
window.requestFileSystem(window.PERSISTENT, 1024 * 1024, function(fs) {
fs.root.getFile(fullPath, {create:false}, function(fileEntry) {
fileEntry.remove(continuneCallback)
})
})
}
function consoleLoglistOfAllFiles() {
listAllFiles(function(entries) {
console.log("- Files -------------------------------");
for(var i = 0;i < entries.length;i++) {
console.log(entries[i].name)
}
})
}
function listAllFiles(callback_listResults) {
window.requestFileSystem(window.PERSISTENT, 1024 * 1024, onInitFs_listAllFiles, fsErrorHandler);
function onInitFs_listAllFiles(fs) {
var dirReader = fs.root.createReader();
var entries = [];
var readEntries = function() {
dirReader.readEntries(function(results) {
if(!results.length) {
callback_listResults(entries)
}else {
entries = entries.concat(Array.prototype.slice.call(results || [], 0));
readEntries()
}
}, fsErrorHandler)
};
readEntries()
}
}
function ActiveSession(continueCallback) {
this.treeModel = null;
this.onRemovedTracker = new OnRemovedTracker;
this.treeModelPersistenceManager = new TreeModelPersistenceManagerIndexedDBAndFilesystem;
var _this = this;
this.treeModelPersistenceManager.restoreTree(function(restoredHierarchy) {
var rootNode = restoredHierarchy;
if(!rootNode) {
rootNode = new NodeSession
}
rootNode.advanceNextDidToValue(localStorage["be_onRestartAdvaceNextDidToLastSentDidForNextDiff"]);
_this.treeModel = extentToTreeModel([rootNode], _this.treeModelPersistenceManager);
_this.applyOnRemovedRecordedBeforeLastSessionExit();
_this.asyncSynchronizeTreeWithOpenWindowsList(function continueInit() {
_this.registerChromeEventsListeners();
continueCallback()
})
})
}
ActiveSession.prototype = {applyOnRemovedRecordedBeforeLastSessionExit:function() {
try {
var tabOnRemovedEvents = this.onRemovedTracker.getTabsOnRemovedEventsFromLastSession();
var tabOnRemovedIds = Object.keys(tabOnRemovedEvents);
for(var i = 0;i < tabOnRemovedIds.length;i++) {
var closedTabId = tabOnRemovedIds[i];
var closedTabClosingInfo = tabOnRemovedEvents[closedTabId];
if(console) {
console.log("APPLY CT", closedTabId, JSON.stringify(closedTabClosingInfo))
}
this.treeModel.onActiveTabRemoved(closedTabId, closedTabClosingInfo, true)
}
var winOnRemovedEvents = this.onRemovedTracker.getWindowsOnRemovedEventsFromLastSession();
var winOnRemovedIds = Object.keys(winOnRemovedEvents);
for(i = 0;i < winOnRemovedIds.length;i++) {
if(console) {
console.log("APPLY CW", winOnRemovedIds[i])
}
this.treeModel.onActiveWindowRemoved(winOnRemovedIds[i], true)
}
}catch(e) {
console.error("ERROR ! AORRBRS", e);
console.log(e["message"]);
console.log(e["stack"])
}
}, asyncSynchronizeTreeWithOpenWindowsList:function(doneCallback) {
var _this = this;
window.chrome.windows.getAll({"populate":true}, function(chromeActiveWindowObjectsList) {
var listOfTabNodesThatMustBeConvertedToSaved = [];
forEachNodeInTree_noChangesInTree(_this.treeModel, function(node) {
if(node.updateChromeTabObjOrRequestConvertToSavedIfNotInActiveList) {
node.updateChromeTabObjOrRequestConvertToSavedIfNotInActiveList(chromeActiveWindowObjectsList, listOfTabNodesThatMustBeConvertedToSaved)
}
});
listOfTabNodesThatMustBeConvertedToSaved.forEach(function(tabNode) {
tabNode.replaceSelfInTreeBy_mergeSubnodesAndMarks(new NodeTabSavedAfterCrash(tabNode.chromeTabObj))
});
var listOfWindowNodesThatMustBeConvertedToSaved = [];
var crashedSavedPopupWindowNodes = [];
forEachNodeInTree_noChangesInTree(_this.treeModel, function(node) {
if(node.updateChromeWindowObjOrConvertToSavedIfNoActiveTabNodesCreated) {
node.updateChromeWindowObjOrConvertToSavedIfNoActiveTabNodesCreated(chromeActiveWindowObjectsList, listOfWindowNodesThatMustBeConvertedToSaved)
}
});
listOfWindowNodesThatMustBeConvertedToSaved.forEach(function(windowNode) {
var newNode = windowNode.replaceSelfInTreeBy_mergeSubnodesAndMarks(new NodeWindowSavedAfterCrash(windowNode.chromeWindowObj));
if(newNode.chromeWindowObj && (newNode.chromeWindowObj.type && newNode.chromeWindowObj.type == "popup")) {
var crashedSavedPopupWinNode = newNode;
if(crashedSavedPopupWinNode.subnodes.length === 1) {
var crashedPopupTab = crashedSavedPopupWinNode.subnodes[0];
if(crashedPopupTab.subnodes.length === 0 && (!crashedPopupTab.isCustomMarksPresent() && !crashedSavedPopupWinNode.isCustomMarksPresent())) {
crashedSavedPopupWinNode.removeOwnTreeFromParent()
}
}
}
});
chromeActiveWindowObjectsList.forEach(function(chromeWindowObj) {
if(!chromeWindowObj.isUsedByNode) {
_this.fromChrome_onWindowCreated(chromeWindowObj)
}else {
delete chromeWindowObj.isUsedByNode
}
chromeWindowObj.tabs.forEach(function(chromeTabObj) {
if(!chromeTabObj.isUsedByNode) {
_this.fromChrome_onTabCreated(chromeTabObj)
}else {
delete chromeTabObj.isUsedByNode
}
});
if(chromeWindowObj.haveActiveTabNodesInTree) {
delete chromeWindowObj.haveActiveTabNodesInTree
}
});
forEachNodeInTree_noChangesInTree(_this.treeModel, function(node) {
if(node.onAfterCrashRestorationDone) {
node.onAfterCrashRestorationDone()
}
});
doneCallback()
})
}, registerChromeEventsListeners:function() {
if(!window.chrome.tabs.onReplaced) {
window.chrome.tabs.onReplaced = {addListener:function(f) {
}}
}
if(debugLogChromeOperations) {
window.chrome.tabs.onCreated.addListener(function(tab) {
console.log("Tab onCreated tabid:" + tab.id + "; url:" + tab.url, tab)
});
window.chrome.tabs.onRemoved.addListener(function(tabId, isWindowClosing) {
console.log("Tab onRemoved tabid:" + tabId + "; isWindowClosingInformation:", isWindowClosing)
});
window.chrome.tabs.onAttached.addListener(function(tabId, attachInfo) {
console.log("Tab onAttached tabid:" + tabId + "; attached to windowid:" + attachInfo.newWindowId, attachInfo)
});
window.chrome.tabs.onDetached.addListener(function(tabId, detachInfo) {
console.log("Tab onDetached tabid:" + tabId + "; detached from windowid:" + detachInfo.oldWindowId, detachInfo)
});
window.chrome.tabs.onMoved.addListener(function(tabId, info) {
console.log("Tab onMoved tabid:" + tabId, info)
});
window.chrome.tabs.onUpdated.addListener(function(tabId, changeInfornamtion, tab) {
console.log("Tab onUpdated tabid:" + tabId + "; url: " + changeInfornamtion.url + "; status: " + changeInfornamtion.status + "; favicon url : " + tab.favIconUrl + "; changeInfornamtion:", changeInfornamtion, "; tab:", tab)
});
window.chrome.tabs.onReplaced.addListener(function(addedTabId, removedTabId) {
console.log("Tab onReplaced addedTabId:", addedTabId, "removedTabId:", removedTabId)
});
window.chrome.tabs.onSelectionChanged.addListener(function(tabId, selectInformation) {
console.log("Tab onSelectionChanged(deprecated) tabid:" + tabId + "; selected in window:" + selectInformation.windowId, selectInformation)
});
window.chrome.tabs.onActivated.addListener(function(activeInfo) {
console.log("Tab onActivated activeInfo:", activeInfo)
});
window.chrome.windows.onCreated.addListener(function(windowObj) {
console.log("Window onCreated winid:" + windowObj.id, windowObj)
});
window.chrome.windows.onRemoved.addListener(function(windowId) {
console.log("Window onRemoved winid:" + windowId)
});
window.chrome.windows.onFocusChanged.addListener(function(windowId) {
console.log("Window onFocusChanged winid:" + windowId + " got focus")
})
}
window.chrome.tabs.onCreated.addListener(this.fromChrome_onTabCreated.bind(this));
window.chrome.tabs.onRemoved.addListener(this.fromChrome_onTabRemoved.bind(this));
window.chrome.tabs.onAttached.addListener(this.fromChrome_onTabAttached.bind(this));
window.chrome.tabs.onDetached.addListener(this.fromChrome_onTabDetached.bind(this));
window.chrome.tabs.onMoved.addListener(this.fromChrome_onTabMoved.bind(this));
window.chrome.tabs.onUpdated.addListener(this.fromChrome_onTabUpdated.bind(this));
window.chrome.tabs.onReplaced.addListener(this.fromChrome_onTabReplaced.bind(this));
window.chrome.tabs.onActivated.addListener(this.fromChrome_onTabActivated.bind(this));
window.chrome.windows.onCreated.addListener(this.fromChrome_onWindowCreated.bind(this));
window.chrome.windows.onRemoved.addListener(this.fromChrome_onWindowRemoved.bind(this));
window.chrome.windows.onFocusChanged.addListener(this.fromChrome_onWindowFocusChanged.bind(this));
window.chrome.tabs.onCreated.addListener(updateBrowserActionTitle);
window.chrome.tabs.onRemoved.addListener(updateBrowserActionTitle);
window.chrome.windows.onCreated.addListener(updateBrowserActionTitle);
window.chrome.windows.onRemoved.addListener(updateBrowserActionTitle);
window.chrome.runtime.onMessageExternal.addListener(this.fromChrome_onExternalMessage.bind(this))
}, fromChrome_onExternalMessage:function(request, sender, sendResponse) {
console.log("ExternalRequest:", request, sender);
sendResponse({"isTrialExpired":true})
}, fromChrome_onTabReplaced:function(addedTabId, removedTabId) {
var newTabNode = this.treeModel.onTabIdReplaced(removedTabId, addedTabId);
if(!newTabNode) {
return
}
window.chrome.tabs.get(newTabNode.chromeTabObj.id, function(chromeTabObj) {
if(chromeTabObj) {
newTabNode.updateChromeTabObj(chromeTabObj)
}
})
}, fromChrome_onTabCreated:function(chromeTabObj) {
var nodeModelForAffectedWindow = this.treeModel.findActiveWindow(chromeTabObj.windowId);
if(!nodeModelForAffectedWindow) {
console.error("ERROR############# onTabCreated # Cannot find window in tree with windowId: " + chromeTabObj.windowId, chromeTabObj)
}
return nodeModelForAffectedWindow.fromChrome_onTabCreated(chromeTabObj, !!localStorage["relateNewTabToOpener"])
}, fromChrome_onWindowCreated:function(chromeWindowObj) {
this.treeModel[0].insertAsLastSubnode(new NodeWindowActive(chromeWindowObj))
}, fromChrome_onTabAttached:function(tabId, attachInfo) {
var windowNode = this.treeModel.findActiveWindow(attachInfo.newWindowId);
if(!windowNode) {
console.error("ERROR fromChrome_onTabAttached attachInfo.newWindowId has no coresponding windowNode in tree");
return
}
var corespondingTabNodeInTargetWindow = windowNode.findAlifeTabInOwnTabsById(tabId);
if(corespondingTabNodeInTargetWindow) {
if(debugLogChromeOperations) {
console.log("This Is Tabs Move Initiated By Our Extention Or Chrome Initiated In One Window ReAttach")
}
var corespondingTabNodeInTargetWindow_chromeTabObj = corespondingTabNodeInTargetWindow.chromeTabObj;