forked from Noitidart/NativeShot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbootstrap.js
More file actions
2420 lines (2117 loc) · 80.5 KB
/
Copy pathbootstrap.js
File metadata and controls
2420 lines (2117 loc) · 80.5 KB
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
// Imports
const {classes: Cc, interfaces: Ci, manager: Cm, results: Cr, utils: Cu, Constructor: CC} = Components;
Cu.import('resource://gre/modules/AddonManager.jsm');
Cu.import('resource://gre/modules/osfile.jsm');
Cu.import('resource://gre/modules/Services.jsm');
Cu.import('resource://gre/modules/XPCOMUtils.jsm');
Cu.importGlobalProperties(['Blob', 'URL']);
const COMMONJS_URI = 'resource://gre/modules/commonjs';
const { require } = Cu.import(COMMONJS_URI + '/toolkit/require.js', {});
var CLIPBOARD = require('sdk/clipboard');
var BEAUTIFY = {};
(function() {
var { require } = Cu.import('resource://devtools/shared/Loader.jsm', {});
var { jsBeautify } = require('devtools/shared/jsbeautify/src/beautify-js');
BEAUTIFY.js = jsBeautify;
}());
// Lazy Imports
var myServices = {};
XPCOMUtils.defineLazyGetter(myServices, 'as', () => Cc['@mozilla.org/alerts-service;1'].getService(Ci.nsIAlertsService) );
var nsIFile = CC('@mozilla.org/file/local;1', Ci.nsILocalFile, 'initWithPath');
// Globals
var core = {
addon: {
name: 'NativeShot',
id: 'NativeShot@jetpack',
version: null, // populated by `startup`
path: {
name: 'nativeshot',
//
content: 'chrome://nativeshot/content/',
locale: 'chrome://nativeshot/locale/',
//
resources: 'chrome://nativeshot/content/resources/',
images: 'chrome://nativeshot/content/resources/images/',
scripts: 'chrome://nativeshot/content/resources/scripts/',
styles: 'chrome://nativeshot/content/resources/styles/',
fonts: 'chrome://nativeshot/content/resources/styles/fonts/',
pages: 'chrome://nativeshot/content/resources/pages/'
// below are added by worker
// storage: OS.Path.join(OS.Constants.Path.profileDir, 'jetpack', core.addon.id, 'simple-storage')
},
cache_key: Math.random()
},
os: {
// // name: added by worker
// // mname: added by worker
toolkit: Services.appinfo.widgetToolkit.toLowerCase(),
xpcomabi: Services.appinfo.XPCOMABI
},
firefox: {
pid: Services.appinfo.processID,
version: Services.appinfo.version,
channel: Services.prefs.getCharPref('app.update.channel')
},
nativeshot: {
services: {
imguranon: {
code: 0,
type: 'upload',
datatype: 'png_arrbuf'
},
twitter: {
code: 1,
type: 'share',
datatype: 'png_arrbuf'
},
copy: {
code: 2,
type: 'system',
datatype: 'png_arrbuf',
noimg: true // no associated image file to show on history page
},
print: {
code: 3,
type: 'system',
datatype: 'png_arrbuf',
noimg: true
},
savequick: {
code: 4,
type: 'system',
datatype: 'png_arrbuf'
},
savebrowse: {
code: 5,
type: 'system',
datatype: 'png_arrbuf'
},
tineye: {
code: 7,
type: 'search',
datatype: 'png_arrbuf',
noimg: true
},
googleimages: {
code: 8,
type: 'search',
datatype: 'png_arrbuf',
noimg: true
},
dropbox: {
code: 9,
type: 'upload',
datatype: 'png_arrbuf'
},
imgur: {
code: 10,
type: 'upload',
datatype: 'png_arrbuf'
},
gdrive: {
code: 11,
type: 'upload',
datatype: 'png_arrbuf'
},
gocr: {
code: 12,
type: 'ocr',
datatype: 'plain_arrbuf',
noimg: true
},
ocrad: {
code: 13,
type: 'ocr',
datatype: 'plain_arrbuf',
noimg: true
},
tesseract: {
code: 14,
type: 'ocr',
datatype: 'plain_arrbuf',
noimg: true
},
ocrall: {
code: 15,
type: 'ocr',
datatype: 'plain_arrbuf',
noimg: true,
history_ignore: true
},
bing: {
code: 16,
type: 'search',
datatype: 'png_arrbuf',
noimg: true
},
facebook: {
code: 17,
type: 'share',
datatype: 'png_arrbuf'
}
}
}
};
var gWkComm;
var gFsComm;
var callInMainworker, callInContentinframescript, callInFramescript;
var gAndroidMenuIds = [];
var gCuiCssUri;
var gGenCssUri;
var OSStuff = {};
var gSession = {
// id: null - set when a session is in progress,
// shots: collMonInfos,
// domwin_wk - most recent browser window when session started
// domwin_was_focused - was it focused when session started
};
var gAttn = {}; // key is session id
var ostypes;
var gFonts;
var gEditorStateStr;
const NS_HTML = 'http://www.w3.org/1999/xhtml';
const NS_XUL = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul';
function install() {}
function uninstall(aData, aReason) {
if (aReason == ADDON_UNINSTALL) {
// we have to access the locale pacage with jar path, as at this point chrome:// doesnt work
var lang = 'rawr'; // Services.prefs.getCharPref('general.useragent.locale');
var jarpath_main_properties = __SCRIPT_URI_SPEC__.replace('/bootstrap.js', '/locale/' + lang + '/main.properties'); // TODO: figure out the `lang` that is used when picking `chrome` package, like if it doesnt find `en` it falls back to closest which is like `en-US`, figure that calculation out
var jarpath_enus_main_properties = __SCRIPT_URI_SPEC__.replace('/bootstrap.js', '/locale/en-US/main.properties');
// __SCRIPT_URI_SPEC__ == jar:file:///C:/Users/Mercurius/AppData/Roaming/Mozilla/Firefox/Profiles/cx4w5lvy.Nightly%20Tester/extensions/NativeShot@jetpack.xpi!/bootstrap.js
// now get contents of the file
// needs to sync, its amo-reviewer ok, as im accessing local file
// needs to be sync because as soon as `uninstall` procedure is done i cannot access files via `jar:` path either, and i need the locale file
var xhr = Cc['@mozilla.org/xmlextras/xmlhttprequest;1'].createInstance(Ci.nsIXMLHttpRequest);
// first try per pref
xhr.open('GET', jarpath_main_properties, false);
try {
xhr.send();
} catch (ex if ex.result == Cr.NS_ERROR_FILE_NOT_FOUND) {
console.error('ex:', ex, 'xhr:', xhr);
// ex: Exception { message: "", result: 2152857618, name: "NS_ERROR_FILE_NOT_FOUND", filename: "resource://gre/modules/addons/XPIPr…", lineNumber: 205, columnNumber: 0, data: null, stack: "uninstall@resource://gre/modules/ad…", location: XPCWrappedNative_NoHelper } xhr: XMLHttpRequest { onreadystatechange: null, readyState: 1, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, responseURL: "", status: 0, statusText: "", responseType: "", response: "" }
// ok fallback to en-US
xhr.open('GET', jarpath_enus_main_properties, false);
xhr.send();
}
console.log('xhr:', xhr);
// xhr: XMLHttpRequest { onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, responseURL: "jar:file:///C:/Users/Mercurius/AppD…", status: 200, statusText: "OK", responseType: "", response: "addon_name=NativeShot addon_descrip…" }
var packageStr = xhr.response;
// bottom is taken from worker `formatStringFromName`
var packageJson = {};
var propPatt = /(.*?)=(.*?)$/gm;
var propMatch;
while (propMatch = propPatt.exec(packageStr)) {
packageJson[propMatch[1]] = propMatch[2];
}
// end taken from worker
var should_delete = Services.prompt.confirmEx(Services.wm.getMostRecentWindow('navigator:browser'), packageJson.uninstall_title, packageJson.uninstall_body.replace(/\\n/g, '\n'), Services.prompt.BUTTON_POS_0 * Services.prompt.BUTTON_TITLE_IS_STRING + Services.prompt.BUTTON_POS_1 * Services.prompt.BUTTON_TITLE_IS_STRING, packageJson.delete, packageJson.keep, '', null, {value: false});
if (should_delete === 0) {
OS.File.removeDir(OS.Path.join(OS.Constants.Path.profileDir, 'jetpack', core.addon.id), {ignorePermissions:true, ignoreAbsent:true}); // will reject if `jetpack` folder does not exist
}
}
}
function startup(aData, aReason) {
core.addon.version = aData.version;
Services.scriptloader.loadSubScript(core.addon.path.scripts + 'comm/Comm.js');
({ callInMainworker, callInContentinframescript, callInFramescript } = CommHelper.bootstrap);
Services.scriptloader.loadSubScript(core.addon.path.scripts + 'jscSystemHotkey/shtkMainthreadSubscript.js');
gWkComm = new Comm.server.worker(core.addon.path.scripts + 'MainWorker.js?' + core.addon.cache_key, ()=>core, function(aArg, aComm) {
({ core } = aArg);
gFsComm = new Comm.server.framescript(core.addon.id);
Services.mm.loadFrameScript(core.addon.path.scripts + 'MainFramescript.js?' + core.addon.cache_key, true);
// desktop:insert_gui
if (core.os.name != 'android') {
gGenCssUri = Services.io.newURI(core.addon.path.styles + 'general.css', null, null);
gCuiCssUri = Services.io.newURI(core.addon.path.styles + getCuiCssFilename(), null, null);
// insert cui
Cu.import('resource:///modules/CustomizableUI.jsm');
CustomizableUI.createWidget({
id: 'cui_' + core.addon.path.name,
defaultArea: CustomizableUI.AREA_NAVBAR,
label: formatStringFromNameCore('gui_label', 'main'),
tooltiptext: formatStringFromNameCore('gui_tooltip', 'main'),
onCommand: guiClick
});
}
// register must go after the above, as i set gCuiCssUri above
windowListener.register();
if (core.os.name != 'android') {
Services.scriptloader.loadSubScript(core.addon.path.scripts + 'react-mozNotificationBar/host.js');
AB.init();
}
}, function() {
var deferredmain = new Deferred();
callInMainworker('hotkeysShouldUnregister', undefined, done=>deferredmain.resolve());
return deferredmain.promise;
});
callInMainworker('dummyForInstantInstantiate');
}
function shutdown(aData, aReason) {
callInMainworker('writeFilestore'); // do even on APP_SHUTDOWN
if (aReason == APP_SHUTDOWN) {
return;
}
Services.mm.removeDelayedFrameScript(core.addon.path.scripts + 'MainFramescript.js?' + core.addon.cache_key);
Comm.server.unregAll('framescript');
Comm.server.unregAll('worker');
// desktop_android:insert_gui
if (core.os.name != 'android') {
CustomizableUI.destroyWidget('cui_' + core.addon.path.name);
} else {
for (var androidMenu of gAndroidMenus) {
var domwin = getStrongReference(androidMenu.domwin);
if (!domwin) {
// its dead
continue;
}
domwin.NativeWindow.menu.remove(androidMenu.menuid);
}
}
windowListener.unregister();
AB.uninit();
releaseAllResourceURI();
}
// start - addon functions
function getCuiCssFilename() {
var cuiCssFilename;
if (Services.prefs.getCharPref('app.update.channel') == 'aurora') {
if (core.os.mname != 'darwin') {
// i didnt test dev edition on winxp, not sure what it is there
cuiCssFilename = 'cui_dev.css';
} else {
cuiCssFilename = 'cui_dev_mac.css';
}
} else {
if (core.os.mname == 'darwin') {
cuiCssFilename = 'cui_mac.css';
} else if (core.os.mname == 'gtk') {
cuiCssFilename = 'cui_gtk.css';
} else {
// windows
if (core.os.version <= 5.2) {
// xp
cuiCssFilename = 'cui_gtk.css';
} else {
cuiCssFilename = 'cui.css';
}
}
}
return cuiCssFilename;
}
function guiClick(e) {
if (!gSession.id) {
if (e.shiftKey) {
// add delay
callInMainworker('countdownStartOrIncrement', 5, function(aArg) {
var { sec_left, done } = aArg;
if (done) {
// countdown done
guiSetBadge(null);
guiClick({});
} else {
// done is false or undefined
// if false it means it was incremented and its closing the pathway. but it sends a sec_left with it, which is the newly incremented countdown
// OR it means it was cancelled. when cancelled there is no sec_left
// if undefined then sec_left is there, and they are providing progress updates
if (sec_left !== undefined) {
// progress, or increment close
guiSetBadge(sec_left);
}
else { console.log('cancelled - pathway cleaned up') }
}
});
} else {
// clear delay if there was one
callInMainworker('countdownCancel', undefined, function(aArg) {
var cancelled = aArg;
if (cancelled) {
guiSetBadge(null);
}
});
takeShot();
}
}
else { console.warn('editor is currently open, so do nothing') }
}
function guiSetBadge(aTxt) {
// set aTxt to null if you want to remove badge
var widgetInstances = CustomizableUI.getWidget('cui_' + core.addon.path.name).instances;
for (var i=0; i<widgetInstances.length; i++) {
var inst = widgetInstances[i];
var node = inst.node;
if (aTxt === null) {
node.classList.remove('badged-button');
node.removeAttribute('badge');
} else {
node.setAttribute('badge', aTxt);
node.classList.add('badged-button'); // classList.add does not add duplicate classes
}
}
}
function takeShot() {
gSession.id = Date.now();
// start - async-proc939333
var shots;
var allMonDimStr;
var shootAllMons = function() {
callInMainworker('shootAllMons', undefined, function(aArg) {
var { collMonInfos } = aArg;
for (var i=0; i<collMonInfos.length; i++) {
collMonInfos[i].arrbuf = aArg['arrbuf' + i];
collMonInfos[i].port1 = aArg['screenshot' + i + '_port1'];
collMonInfos[i].port2 = aArg['screenshot' + i + '_port2'];
}
// call it shots
shots = collMonInfos;
gSession.shots = shots;
// the most recent browser window when screenshot was taken
var domwin = Services.wm.getMostRecentWindow('navigator:browser');
gSession.domwin_wk = Cu.getWeakReference(domwin);
gSession.domwin = domwin;
gSession.domwin_was_focused = isFocused(domwin);
// create allMonDimStr
var allMonDim = [];
for (var shot of shots) {
allMonDim.push({
x: shot.x,
y: shot.y,
w: shot.w,
h: shot.h
// win81ScaleX: shot.win81ScaleX,
// win81ScaleY: shot.win81ScaleY
});
}
allMonDimStr = JSON.stringify(allMonDim);
ensureGlobalEditorstate();
});
};
var ensureGlobalEditorstate = function() {
if (!gEditorStateStr) {
callInMainworker('fetchFilestoreEntry', {mainkey:'editorstate'}, function(aArg) {
gEditorStateStr = JSON.stringify(aArg);
openEditorWins();
});
} else {
openEditorWins();
}
};
var openEditorWins = function() {
// open window for each shot
var i = -1;
for (var shot of shots) {
i++;
var x = shot.x;
var y = shot.y;
var w = shot.w;
var h = shot.h;
// scale it?
var scaleX = shot.win81ScaleX;
var scaleY = shot.win81ScaleY;
if (scaleX) {
x = Math.floor(x / scaleX);
w = Math.floor(w / scaleX);
}
if (scaleY) {
y = Math.floor(y / scaleY);
h = Math.floor(h / scaleY);
}
// make query string of the number, string, and boolean properties of shot
var query_json = Object.assign(
{
iMon: i,
allMonDimStr: allMonDimStr,
sessionid: gSession.id
},
shot
);
// console.log('query_json:', query_json);
var query_str = jQLike.serialize(query_json);
// console.log('query_str:', query_str);
var editor_domwin = Services.ww.openWindow(null, 'about:nativeshot?' + query_str, '_blank', 'chrome,titlebar=0,width=' + w + ',height=' + h + ',screenX=' + x + ',screenY=' + y, null);
// editor_domwin.addEventListener('load', function() {
// editor_domwin.document.documentElement.style.backgroundColor = 'green';
// }, false);
shot.domwin_wk = Cu.getWeakReference(editor_domwin);
shot.domwin = editor_domwin;
}
};
shootAllMons();
// end - async-proc939333
}
// start - functions called by editor
function editorInitShot(aIMon, e) {
// does the platform dependent stuff to make the window be position on the proper monitor and full screened covering all things underneeath
// also transfer the screenshot data to the window
// console.error('e:', e);
var iMon = aIMon; // iMon is my rename of colMonIndex. so its the i in the collMoninfos object
var shots = gSession.shots;
var shot = shots[iMon];
// var aEditorDOMWindow = colMon[iMon].E.DOMWindow;
//
// if (!aEditorDOMWindow || aEditorDOMWindow.closed) {
// throw new Error('wtf how is window not existing, the on load observer notifier of panel.xul just sent notification that it was loaded');
// }
var domwin = getStrongReference(shot.domwin_wk);
if (!domwin) {
Services.prompt(null, 'domwin of shot is dead', 'dead');
}
var domwin = shot.domwin;
var aHwndPtrStr = getNativeHandlePtrStr(domwin);
console.error('aHwndPtrStr.pre method1:', getNativeHandlePtrStr(domwin), 'method2:', getNativeHandlePtrStr(e.target));
shot.hwndPtrStr = aHwndPtrStr;
// if (core.os.name != 'darwin') {
// aEditorDOMWindow.moveTo(colMon[iMon].x, colMon[iMon].y);
// aEditorDOMWindow.resizeTo(colMon[iMon].w, colMon[iMon].h);
// }
domwin.focus();
// if (core.os.name != 'darwin') {
// aEditorDOMWindow.fullScreen = true;
// }
// set window on top:
var aArrHwndPtrStr = [aHwndPtrStr];
var aArrHwndPtrOsParams = {};
aArrHwndPtrOsParams[aHwndPtrStr] = {
left: shot.x,
top: shot.y,
right: shot.x + shot.w,
bottom: shot.y + shot.h,
width: shot.w,
height: shot.h
};
// if (core.os.name != 'darwinAAAA') {
callInMainworker('setWinAlwaysOnTop', { aArrHwndPtrStr, aOptions:aArrHwndPtrOsParams }, function(aArg) {
console.error('post for logging aHwndPtrStr, core.os:', core.os);
if (core.os.name == 'darwin') {
console.error('in darwin block of post for logging aHwndPtrStr');
initOstypes();
// link98476884
OSStuff.NSMainMenuWindowLevel = aArg;
var NSWindowString = aHwndPtrStr;
console.error('aHwndPtrStr.post method1:', getNativeHandlePtrStr(domwin), 'method2:', getNativeHandlePtrStr(e.target));
// var NSWindowString = getNativeHandlePtrStr(domwin);
var NSWindowPtr = ostypes.TYPE.NSWindow(ctypes.UInt64(NSWindowString));
var rez_setLevel = ostypes.API('objc_msgSend')(NSWindowPtr, ostypes.HELPER.sel('setLevel:'), ostypes.TYPE.NSInteger(OSStuff.NSMainMenuWindowLevel + 1)); // have to do + 1 otherwise it is ove rmneubar but not over the corner items. if just + 0 then its over menubar, if - 1 then its under menu bar but still over dock. but the interesting thing is, the browse dialog is under all of these // link847455111
console.log('rez_setLevel:', rez_setLevel.toString());
var newSize = ostypes.TYPE.NSSize(shot.w, shot.h);
var rez_setContentSize = ostypes.API('objc_msgSend')(NSWindowPtr, ostypes.HELPER.sel('setContentSize:'), newSize);
console.log('rez_setContentSize:', rez_setContentSize.toString());
domwin.moveTo(shot.x, shot.y); // must do moveTo after setContentsSize as that sizes from bottom left and moveTo moves from top left. so the sizing will change the top left.
}
});
if (!gFonts) {
var fontsEnumerator = Cc['@mozilla.org/gfx/fontenumerator;1'].getService(Ci.nsIFontEnumerator);
gFonts = fontsEnumerator.EnumerateAllFonts({});
}
shot.comm.putMessage('init', {
screenshotArrBuf: shot.arrbuf,
core: core,
fonts: gFonts,
editorstateStr: gEditorStateStr,
_XFER: ['screenshotArrBuf']
});
// set windowtype attribute
// colMon[aData.iMon].E.DOMWindow.document.documentElement.setAttribute('windowtype', 'nativeshot:canvas');
// check to see if all monitors inited, if they have been, the fetch all win
var allWinInited = true;
for (var shoty of shots) {
if (!shoty.hwndPtrStr) {
allWinInited = false;
break;
}
}
if (allWinInited) {
if (core.os.mname == 'winnt') {
// reRaiseCanvasWins(); // ensures its risen
}
sendWinArrToEditors();
}
}
function sendWinArrToEditors() {
var shots = gSession.shots;
callInMainworker(
'getAllWin',
{
getPid: true,
getBounds: true,
getTitle: true,
filterVisible: true
},
function(aVal) {
console.log('Fullfilled - promise_fetchWin - ', aVal);
// Cc["@mozilla.org/widget/clipboardhelper;1"].getService(Ci.nsIClipboardHelper).copyString(JSON.stringify(aVal)); // :debug:
// build hwndPtrStr arr for nativeshot_canvas windows
var hwndPtrStrArr = [];
for (var shot of shots) {
hwndPtrStrArr.push(shot.hwndPtrStr);
}
// remove nativeshot_canvas windows
for (var i=0; i<aVal.length; i++) {
if (aVal[i].title == 'nativeshot_canvas' || hwndPtrStrArr.indexOf(aVal[i].hwndPtrStr) > -1) {
// need to do the hwndPtrStr check as on windows, sometimes the page isnt loaded yet, so the title of the window isnt there yet
// aVal.splice(i, 1);
aVal[i].left = -10000;
aVal[i].right = -10000;
aVal[i].width = 0;
aVal[i].NATIVESHOT_CANVAS = true;
// i--;
}
}
for (var shot of shots) {
shot.comm.putMessage('receiveWinArr', {
winArr: aVal
});
}
}
);
}
function broadcastToOthers(aArg) {
var { iMon } = aArg;
var shots = gSession.shots; // TODO: sometimes i get this error in console `TypeError: shots is undefined[Learn More]bootstrap.js:596:6` baffling, i need to figure out how to fix this, it doesnt seem to cause issues that i can find
// console.log('gSession:', gSession);
var l = shots.length;
for (var i=0; i<l; i++) {
if (i !== iMon) {
shots[i].comm.putMessage(aArg.topic, aArg);
}
}
}
function broadcastToSpecific(aArg) {
var { toMon } = aArg;
var shot = gSession.shots[toMon];
shot.comm.putMessage(aArg.topic, aArg);
}
function exitEditors(aArg) {
var { iMon, editorstateStr } = aArg;
var shots = gSession.shots;
var l = shots.length;
for (var i=0; i<l; i++) {
if (i !== iMon) {
var domwin = getStrongReference(shots[i].domwin_wk);
if (!domwin) {
console.error('no domwin for shot:', i, 'shots:', shots);
// Services.prompt.alert(null, 'huh', 'weak ref is dead??');
}
shots[i].comm.putMessage('removeUnload', undefined, function(adomwin) {
adomwin.close();
}.bind(null, shots[i].domwin));
}
}
// // as nativeshot_canvas windows are now closing. check if should show notification bar - if it has any btns then show it
// if (gEditorABData_Bar[gEditor.sessionId].ABRef.aBtns.length) {
// console.log('need to show notif bar now');
// gEditorABData_Bar[gEditor.sessionId].shown = true; // otherwise setBtnState will not update react states
// AB.setState(gEditorABData_Bar[gEditor.sessionId].ABRef);
// ifEditorClosed_andBarHasOnlyOneAction_copyToClip(gEditor.sessionId);
// } else {
// // no need to show, delete it
// console.log('no need to show, delete it');
// delete gEditorABData_Bar[gEditor.sessionId];
// }
//
// // check if need to show twitter notification bars
// for (var p in NBs.crossWin) {
// if (p.indexOf(gEditor.sessionId) == 0) { // note: this is why i have to start each crossWin id with gEditor.sessionId
// NBs.insertGlobalToWin(p, 'all');
// }
// }
// if (gEditor.wasFirefoxWinFocused || gEditor.forceFocus) {
// gEditor.gBrowserDOMWindow.focus();
// }
// if (gEditor.printPrevWins) {
// for (var i=0; i<gEditor.printPrevWins.length; i++) {
// gEditor.printPrevWins[i].focus();
// }
// }
// // colMon[0].E.DOMWindow.close();
var sessionid = gSession.id;
gSession = {}; // gEditor.cleanUp();
attnUpdate(sessionid); // show the attnbar if there is anything to show
console.error('will now checkOnlySingleAction as have shown it for sure, well i think but its not true'); // TODO: figure out whye gAttn[sessionid] is undefined here
checkOnlySingleAction(sessionid, true);
gEditorStateStr = JSON.stringify(aArg.editorstate);
console.log('set gEditorStateStr to:', gEditorStateStr);
callInMainworker('updateFilestoreEntry', {
mainkey: 'editorstate',
value: aArg.editorstate
});
if (core.os.mname == 'gtk') {
callInMainworker('gtkSetFocus', getNativeHandlePtrStr(Services.wm.getMostRecentWindow('navigator:browser')));
}
}
var gUsedSelections = []; // array of arrays. each child is [subcutout1, subcutout2, ...]
function indexOfSelInG(aSel) {
// aSel is an array of subcutouts
// will return the index it is found in gUsedSelections
// -1 if not found
var l = gUsedSelections.length;
if (!l) {
return -1;
} else {
for (var i=l-1; i>=0; i--) {
var tSel = gUsedSelections[i]; // testSelection
var l2 = tSel.length;
if (l2 === aSel.length) {
var tSelMatches = true;
for (var j=0; j<l2; j++) {
var tSubcutout = tSel[j];
var cSubcutout = aSel[j];
console.log('comparing', 'tSel:', tSel, 'aSel:', aSel);
if (tSubcutout.x !== cSubcutout.x || tSubcutout.y !== cSubcutout.y || tSubcutout.w !== cSubcutout.w || tSubcutout.h !== cSubcutout.h) {
// tSel does not match aSel
tSelMatches = false;
break;
}
}
if (tSelMatches) {
return i;
}
}
}
return -1; // not found
}
}
function addSelectionToHistory(aData) {
// aData.cutoutsArr is an array of cutouts
console.log('incoming addSelectionToHistory:', aData);
var cSel = aData.cutoutsArr;
var ix = indexOfSelInG(cSel);
if (ix == -1) {
gUsedSelections.push(aData.cutoutsArr)
} else {
// it was found in history, so lets move this to the most recent selection made
// most recent selection is the last most element in gUsedSelections array
gUsedSelections.push(gUsedSelections.splice(ix, 1)[0]);
}
console.log('added sel, now gUsedSelections:', gUsedSelections);
}
function selectPreviousSelection(aData) {
// aData.curSelection is an array of the currently selected cutouts
if (!gUsedSelections.length) {
return;
}
var cSel = aData.cutoutsArr; // cutouts of the current selection
// figure out the selection to make
var selToMake;
if (cSel) {
// check to see if this sel is in the history, and select the one before this one
var ix = indexOfSelInG(cSel);
if (ix > 0) {
selToMake = gUsedSelections[ix - 1];
} else if (ix == -1) {
// select the most recent one
selToMake = gUsedSelections[gUsedSelections.length - 1];
} // else if 0, then no previous selection obviously
} else {
// select the most recent one
selToMake = gUsedSelections[gUsedSelections.length - 1];
}
// send message to make the selection
if (selToMake) {
gSession.shots[aData.iMon].comm.putMessage('makeSelection', {
cutoutsArr: selToMake
}, '*');
}
}
// end - last selection stuff
function insertTextFromClipboard(aArg) {
var { iMon } = aArg;
if (CLIPBOARD.currentFlavors.indexOf('text') > -1) {
gSession.shots[iMon].comm.putMessage('insertTextFromClipboard', {
text: CLIPBOARD.get('text')
}, '*');
}
}
// end - functions called by editor
function initOstypes() {
if (!ostypes) {
Cu.import('resource://gre/modules/ctypes.jsm');
Services.scriptloader.loadSubScript(core.addon.path.scripts + 'ostypes/cutils.jsm'); // need to load cutils first as ostypes_mac uses it for HollowStructure
Services.scriptloader.loadSubScript(core.addon.path.scripts + 'ostypes/ctypes_math.jsm');
switch (core.os.mname) {
case 'winnt':
case 'winmo':
case 'wince':
Services.scriptloader.loadSubScript(core.addon.path.scripts + 'ostypes/ostypes_win.jsm');
break;
case 'gtk':
Services.scriptloader.loadSubScript(core.addon.path.scripts + 'ostypes/ostypes_x11.jsm');
break;
case 'darwin':
Services.scriptloader.loadSubScript(core.addon.path.scripts + 'ostypes/ostypes_mac.jsm');
break;
default:
throw new Error('Operating system, "' + OS.Constants.Sys.Name + '" is not supported');
}
}
}
// start - context menu items
var gToolbarContextMenu_domId = 'toolbar-context-menu';
var gCustomizationPanelItemContextMenu_domId = 'customizationPanelItemContextMenu';
var gDashboardMenuitem_domIdSuffix = '_nativeshot-menuitem';
var gDashboardSeperator_domIdSuffix = '_nativeshot-seperator';
var gDashboardMenuitem_jsonTemplate = ['xul:menuitem', {
// id: 'toolbar-context-menu_nativeshot-menuitem',
// label: formatStringFromNameCore('dashboard-menuitem', 'main'), // cant access myServices.sb till startup, so this is set on startup // link988888887
class: 'menuitem-iconic',
image: core.addon.path.images + 'icon16.png',
hidden: 'true',
oncommand: function(e) {
var gbrowser = e.target.ownerDocument.defaultView.gBrowser;
var tabs = gbrowser.tabs;
var l = gbrowser.tabs.length;
for (var i=0; i<l; i++) {
// e10s safe way to check content of tab
var spec_lower = tabs[i].linkedBrowser.currentURI.spec.toLowerCase();
if (spec_lower == 'about:nativeshot') { // crossfile-link381787872 - i didnt link over there but &nativeshot.app-main.title; is what this is equal to
gbrowser.selectedTab = tabs[i];
return;
}
}
gbrowser.loadOneTab('about:nativeshot', {inBackground:false});
}
}];
var gDashboardMenuseperator_jsonTemplate = ['xul:menuseparator', {
// id: 'toolbar-context-menu_nativeshot-menuseparator', // id is set when inserting into dom
hidden: 'true'
}];
function contextMenuHiding(e) {
// only triggered when it was shown due to right click on cui_nativeshot
console.log('context menu hiding');
e.target.removeEventListener('popuphiding', contextMenuHiding, false);
var cToolbarContextMenu_dashboardMenuitem = e.target.querySelector('#' + gToolbarContextMenu_domId + gDashboardMenuitem_domIdSuffix);
if (cToolbarContextMenu_dashboardMenuitem) {
var cToolbarContextMenu_dashboardSeperator = e.target.querySelector('#' + gToolbarContextMenu_domId + gDashboardSeperator_domIdSuffix);
cToolbarContextMenu_dashboardMenuitem.setAttribute('hidden', 'true');
cToolbarContextMenu_dashboardSeperator.setAttribute('hidden', 'true');
}
var cCustomizationPanelItemContextMenu_dashboardMenuitem = e.target.querySelector('#' + gCustomizationPanelItemContextMenu_domId + gDashboardMenuitem_domIdSuffix);
if (cCustomizationPanelItemContextMenu_dashboardMenuitem) {
var cCustomizationPanelItemContextMenu_dashboardSeperator = e.target.querySelector('#' + gCustomizationPanelItemContextMenu_domId + gDashboardSeperator_domIdSuffix);
cCustomizationPanelItemContextMenu_dashboardMenuitem.setAttribute('hidden', 'true');
cCustomizationPanelItemContextMenu_dashboardMenuitem.setAttribute('hidden', 'true');
}
}
function contextMenuShowing(e) {
console.log('context menu showing', 'popupNode:', e.target.ownerDocument.popupNode);
var cPopupNode = e.target.ownerDocument.popupNode;
if (cPopupNode.getAttribute('id') == 'cui_nativeshot') {
var cToolbarContextMenu_dashboardMenuitem = e.target.querySelector('#' + gToolbarContextMenu_domId + gDashboardMenuitem_domIdSuffix);
if (cToolbarContextMenu_dashboardMenuitem) {
var cToolbarContextMenu_dashboardSeperator = e.target.querySelector('#' + gToolbarContextMenu_domId + gDashboardSeperator_domIdSuffix);
cToolbarContextMenu_dashboardMenuitem.removeAttribute('hidden');
cToolbarContextMenu_dashboardSeperator.removeAttribute('hidden');
e.target.addEventListener('popuphiding', contextMenuHiding, false);
}
var cCustomizationPanelItemContextMenu_dashboardMenuitem = e.target.querySelector('#' + gCustomizationPanelItemContextMenu_domId + gDashboardMenuitem_domIdSuffix);
if (cCustomizationPanelItemContextMenu_dashboardMenuitem) {
var cCustomizationPanelItemContextMenu_dashboardSeperator = e.target.querySelector('#' + gCustomizationPanelItemContextMenu_domId + gDashboardSeperator_domIdSuffix);
cCustomizationPanelItemContextMenu_dashboardMenuitem.removeAttribute('hidden');
cCustomizationPanelItemContextMenu_dashboardSeperator.removeAttribute('hidden');
e.target.addEventListener('popuphiding', contextMenuHiding, false);
}
}
}
function contextMenuSetup(aDOMWindow) {
// if this aDOMWindow has the context menus set it up
if (!gDashboardMenuitem_jsonTemplate[1].label) {
gDashboardMenuitem_jsonTemplate[1].label = formatStringFromNameCore('menuitem_opendashboard', 'main'); // link988888887 - needs to go before windowListener is registered
}
var cToolbarContextMenu = aDOMWindow.document.getElementById(gToolbarContextMenu_domId);
if (cToolbarContextMenu) {
gDashboardMenuitem_jsonTemplate[1].id = gToolbarContextMenu_domId + gDashboardMenuitem_domIdSuffix;
gDashboardMenuseperator_jsonTemplate[1].id = gToolbarContextMenu_domId + gDashboardSeperator_domIdSuffix;
var cToolbarContextMenu_dashboardMenuitem = jsonToDOM(gDashboardMenuitem_jsonTemplate, aDOMWindow.document, {});
var cToolbarContextMenu_dashboardSeperator = jsonToDOM(gDashboardMenuseperator_jsonTemplate, aDOMWindow.document, {});
cToolbarContextMenu.insertBefore(cToolbarContextMenu_dashboardSeperator, cToolbarContextMenu.firstChild);
cToolbarContextMenu.insertBefore(cToolbarContextMenu_dashboardMenuitem, cToolbarContextMenu.firstChild);
cToolbarContextMenu.addEventListener('popupshowing', contextMenuShowing, false);
}
var cCustomizationPanelItemContextMenu = aDOMWindow.document.getElementById(gCustomizationPanelItemContextMenu_domId);
if (cCustomizationPanelItemContextMenu) {
gDashboardMenuitem_jsonTemplate[1].id = gCustomizationPanelItemContextMenu_domId + gDashboardMenuitem_domIdSuffix;
gDashboardMenuseperator_jsonTemplate[1].id = gCustomizationPanelItemContextMenu_domId + gDashboardSeperator_domIdSuffix;
var cCustomizationPanelItemContextMenu_dashboardMenuitem = jsonToDOM(gDashboardMenuitem_jsonTemplate, aDOMWindow.document, {});
var cCustomizationPanelItemContextMenu_dashboardSeperator = jsonToDOM(gDashboardMenuseperator_jsonTemplate, aDOMWindow.document, {});
cCustomizationPanelItemContextMenu.insertBefore(cCustomizationPanelItemContextMenu_dashboardSeperator, cCustomizationPanelItemContextMenu.firstChild);
cCustomizationPanelItemContextMenu.insertBefore(cCustomizationPanelItemContextMenu_dashboardMenuitem, cCustomizationPanelItemContextMenu.firstChild);
cCustomizationPanelItemContextMenu.addEventListener('popupshowing', contextMenuShowing, false);
}
// console.log('ok good setup');
}
function contextMenuDestroy(aDOMWindow) {
// if this aDOMWindow has the context menus it removes it from it
var cToolbarContextMenu = aDOMWindow.document.getElementById(gToolbarContextMenu_domId);
if (cToolbarContextMenu) {
var cToolbarContextMenu_dashboardMenuitem = aDOMWindow.document.getElementById(gToolbarContextMenu_domId + gDashboardMenuitem_domIdSuffix);
var cToolbarContextMenu_dashboardSeperator = aDOMWindow.document.getElementById(gToolbarContextMenu_domId + gDashboardSeperator_domIdSuffix);
cToolbarContextMenu.removeChild(cToolbarContextMenu_dashboardMenuitem);
cToolbarContextMenu.removeChild(cToolbarContextMenu_dashboardSeperator);
cToolbarContextMenu.removeEventListener('popupshowing', contextMenuShowing, false);
}
var cCustomizationPanelItemContextMenu = aDOMWindow.document.getElementById(gCustomizationPanelItemContextMenu_domId);
if (cCustomizationPanelItemContextMenu) {
var cCustomizationPanelItemContextMenu_dashboardMenuitem = aDOMWindow.document.getElementById(gCustomizationPanelItemContextMenu_domId + gDashboardMenuitem_domIdSuffix);
var cCustomizationPanelItemContextMenu_dashboardSeperator = aDOMWindow.document.getElementById(gCustomizationPanelItemContextMenu_domId + gDashboardSeperator_domIdSuffix);
cCustomizationPanelItemContextMenu.removeChild(cCustomizationPanelItemContextMenu_dashboardMenuitem);
cCustomizationPanelItemContextMenu.removeChild(cCustomizationPanelItemContextMenu_dashboardSeperator);
cCustomizationPanelItemContextMenu.removeEventListener('popupshowing', contextMenuShowing, false);
}