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
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Tab API implementation.
//
// Tab IDs are the window handle of the "TabWindowClass" window class
// of the whole tab.
//
// To find the chrome.window.* "window ID" we can just get the top-level parent
// window of the tab window.
//
// TODO(joi@chromium.org) Figure out what to do in IE6 (which has no tabs).
#include "ceee/ie/broker/tab_api_module.h"
#include <atlbase.h>
#include <atlcom.h>
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "base/win/scoped_bstr.h"
#include "base/win/scoped_comptr.h"
#include "base/win/scoped_variant.h"
#include "base/win/windows_version.h"
#include "ceee/ie/broker/api_module_constants.h"
#include "ceee/ie/broker/api_module_util.h"
#include "ceee/ie/broker/executors_manager.h"
#include "ceee/ie/common/api_registration.h"
#include "ceee/ie/common/constants.h"
#include "ceee/ie/common/ie_util.h"
#include "chrome/browser/automation/extension_automation_constants.h"
#include "chrome/browser/extensions/extension_event_names.h"
#include "chrome/browser/extensions/extension_tabs_module_constants.h"
#include "chrome/common/extensions/extension_error_utils.h"
#include "chrome/common/url_constants.h"
#include "googleurl/src/gurl.h"
#include "ceee/common/com_utils.h"
#include "ceee/common/window_utils.h"
#include "ceee/common/windows_constants.h"
namespace ext = extension_tabs_module_constants;
namespace ext_event_names = extension_event_names;
namespace keys = extension_automation_constants;
namespace tab_api {
namespace {
// bb3147348
// Convert the tab_id parameter (always the first one) and verify that the
// event received has the right number of parameters.
// NumParam is the number of parameters we expect from events_funnel.
// AddTabParam if true, we add a Tab object to the converted_args.
template<int NumParam, bool AddTabParam>
bool ConvertTabIdEventHandler(const std::string& input_args,
std::string* converted_args,
ApiDispatcher* dispatcher) {
DCHECK(converted_args);
*converted_args = input_args;
// Get the tab ID from the input arguments.
scoped_ptr<ListValue> input_list;
if (!api_module_util::GetListFromJsonString(input_args, &input_list)) {
NOTREACHED() << "Invalid Arguments sent to event.";
return false;
}
if (input_list == NULL || input_list->GetSize() != NumParam) {
NOTREACHED() << "Invalid Number of Arguments sent to event.";
return false;
}
int tab_handle = -1;
bool success = input_list->GetInteger(0, &tab_handle);
DCHECK(success) << "Failed getting the tab_id value from the list of args.";
HWND tab_window = reinterpret_cast<HWND>(tab_handle);
int tab_id = dispatcher->GetTabIdFromHandle(tab_window);
DCHECK(tab_id != kInvalidChromeSessionId);
if (tab_id == kInvalidChromeSessionId)
return false;
input_list->Set(0, Value::CreateIntegerValue(tab_id));
if (AddTabParam) {
TabApiResult result(TabApiResult::kNoRequestId);
// Don't DCHECK here since we have cases where the tab died beforehand.
if (!result.CreateTabValue(tab_id, -1)) {
LOG(ERROR) << "Failed to create a value for tab: " << std::hex << tab_id;
return false;
}
input_list->Append(result.value()->DeepCopy());
}
base::JSONWriter::Write(input_list.get(), false, converted_args);
return true;
}
bool CeeeUnmapTabEventHandler(const std::string& input_args,
std::string* converted_args,
ApiDispatcher* dispatcher) {
int tab_handle = reinterpret_cast<int>(INVALID_HANDLE_VALUE);
scoped_ptr<ListValue> input_list;
if (!api_module_util::GetListAndIntegerValue(input_args, &input_list,
&tab_handle) ||
tab_handle == kInvalidChromeSessionId) {
NOTREACHED() << "An invalid argument was passed to UnmapTab";
return false;
}
#ifdef DEBUG
int tab_id = kInvalidChromeSessionId;
input_list->GetInteger(1, &tab_id);
DCHECK(tab_id == dispatcher->GetTabIdFromHandle(
reinterpret_cast<HWND>(tab_handle)));
#endif // DEBUG
HWND tab_window = reinterpret_cast<HWND>(tab_handle);
dispatcher->DeleteTabHandle(tab_window);
return false;
}
bool GetIdAndHandleFromArgs(const std::string& input_args, int* id,
HWND* handle) {
DCHECK(id != NULL);
DCHECK(handle != NULL);
scoped_ptr<ListValue> input_list;
*id = kInvalidChromeSessionId;
if (!api_module_util::GetListAndIntegerValue(input_args, &input_list, id) ||
*id == kInvalidChromeSessionId) {
NOTREACHED() << "An invalid argument was passed to GetIdAndHandleFromArgs";
return false;
}
int tab_handle = 0;
if (!input_list->GetInteger(1, &tab_handle) || tab_handle == 0) {
NOTREACHED() << "An invalid argument was passed to GetIdAndHandleFromArgs";
return false;
}
*handle = reinterpret_cast<HWND>(tab_handle);
return true;
}
bool CeeeMapTabIdToHandle(const std::string& input_args,
std::string* converted_args,
ApiDispatcher* dispatcher) {
int tab_id = kInvalidChromeSessionId;
HWND tab_handle = NULL;
if (GetIdAndHandleFromArgs(input_args, &tab_id, &tab_handle)) {
ExecutorsManager::GetInstance()->SetTabIdForHandle(tab_id, tab_handle);
return true;
}
return false;
}
bool CeeeMapToolbandIdToHandle(const std::string& input_args,
std::string* converted_args,
ApiDispatcher* dispatcher) {
int toolband_id = kInvalidChromeSessionId;
HWND tab_handle = NULL;
if (GetIdAndHandleFromArgs(input_args, &toolband_id, &tab_handle)) {
ExecutorsManager::GetInstance()->SetTabToolBandIdForHandle(toolband_id,
tab_handle);
return true;
}
return false;
}
} // namespace
void RegisterInvocations(ApiDispatcher* dispatcher) {
#define REGISTER_API_FUNCTION(func) do { dispatcher->RegisterInvocation(\
func##Function::function_name(), NewApiInvocation< func >); }\
while (false)
REGISTER_TAB_API_FUNCTIONS();
#undef REGISTER_API_FUNCTION
// Registers our private events.
dispatcher->RegisterPermanentEventHandler(
ceee_event_names::kCeeeOnTabUnmapped, CeeeUnmapTabEventHandler);
dispatcher->RegisterPermanentEventHandler(
ceee_event_names::kCeeeMapTabIdToHandle, CeeeMapTabIdToHandle);
dispatcher->RegisterPermanentEventHandler(
ceee_event_names::kCeeeMapToolbandIdToHandle, CeeeMapToolbandIdToHandle);
// And now register the permanent event handlers.
dispatcher->RegisterPermanentEventHandler(ext_event_names::kOnTabCreated,
CreateTab::EventHandler);
// For OnTabUpdate, we receive 2 from events_funnel, and add a Tab Parameter.
dispatcher->RegisterPermanentEventHandler(ext_event_names::kOnTabUpdated,
ConvertTabIdEventHandler<2, true>);
dispatcher->RegisterPermanentEventHandler(ext_event_names::kOnTabAttached,
ConvertTabIdEventHandler<2, false>);
dispatcher->RegisterPermanentEventHandler(ext_event_names::kOnTabDetached,
ConvertTabIdEventHandler<2, false>);
dispatcher->RegisterPermanentEventHandler(ext_event_names::kOnTabMoved,
ConvertTabIdEventHandler<2, false>);
dispatcher->RegisterPermanentEventHandler(ext_event_names::kOnTabRemoved,
ConvertTabIdEventHandler<1, false>);
dispatcher->RegisterPermanentEventHandler(
ext_event_names::kOnTabSelectionChanged,
ConvertTabIdEventHandler<2, false>);
}
bool TabApiResult::CreateTabValue(int tab_id, long index) {
ApiDispatcher* dispatcher = GetDispatcher();
DCHECK(dispatcher != NULL);
HWND tab_window = dispatcher->GetTabHandleFromId(tab_id);
if (window_utils::WindowHasNoThread(tab_window)) {
PostError(ExtensionErrorUtils::FormatErrorMessage(
ext::kTabNotFoundError, base::IntToString(tab_id)));
return false;
}
if (!IsTabWindowClass(tab_window)) {
PostError(ExtensionErrorUtils::FormatErrorMessage(
ext::kTabNotFoundError, base::IntToString(tab_id)));
return false;
}
base::win::ScopedComPtr<ICeeeTabExecutor> executor;
dispatcher->GetExecutor(tab_window, IID_ICeeeTabExecutor,
reinterpret_cast<void**>(executor.Receive()));
if (executor == NULL) {
LOG(WARNING) << "Failed to get an executor to get tab info.";
PostError(api_module_constants::kInternalErrorError);
return false;
}
TabInfo tab_info;
HRESULT hr = executor->GetTabInfo(&tab_info);
if (FAILED(hr)) {
LOG(WARNING) << "Executor failed to get tab info." << com::LogHr(hr);
PostError(api_module_constants::kInternalErrorError);
return false;
}
scoped_ptr<DictionaryValue> result(new DictionaryValue());
result->SetInteger(ext::kIdKey, tab_id);
// TODO(mad@chromium.org): Support the pin field.
result->SetBoolean(ext::kPinnedKey, false);
// The window ID is just the window handle of the frame window, which is the
// top-level ancestor of this window.
HWND frame_window = window_utils::GetTopLevelParent(tab_window);
if (frame_window == tab_window ||
!window_utils::IsWindowClass(frame_window,
windows::kIeFrameWindowClass)) {
// If we couldn't get a valid parent frame window, then it must be because
// the frame window (and the tab then) has been closed by now or it lives
// under the hidden IE window.
DCHECK(!::IsWindow(tab_window) || window_utils::IsWindowClass(frame_window,
windows::kHiddenIeFrameWindowClass));
PostError(ExtensionErrorUtils::FormatErrorMessage(
ext::kTabNotFoundError, base::IntToString(tab_id)));
return false;
}
int frame_window_id = dispatcher->GetWindowIdFromHandle(frame_window);
result->SetInteger(ext::kWindowIdKey, frame_window_id);
// Only the currently selected tab has the VS_VISIBLE style.
result->SetBoolean(ext::kSelectedKey, TRUE == ::IsWindowVisible(tab_window));
result->SetString(ext::kUrlKey, com::ToString(tab_info.url));
result->SetString(ext::kTitleKey, com::ToString(tab_info.title));
std::string status = ext::kStatusValueComplete;
if (tab_info.status == kCeeeTabStatusLoading)
status = ext::kStatusValueLoading;
else
DCHECK(tab_info.status == kCeeeTabStatusComplete) << "New Status???";
result->SetString(ext::kStatusKey, status);
if (tab_info.fav_icon_url != NULL) {
result->SetString(ext::kFavIconUrlKey,
com::ToString(tab_info.fav_icon_url));
}
// When enumerating all tabs, we already have the index
// so we can save an IPC call.
if (index == -1) {
// We need another executor to get the index from the frame window thread.
base::win::ScopedComPtr<ICeeeWindowExecutor> executor;
dispatcher->GetExecutor(frame_window, IID_ICeeeWindowExecutor,
reinterpret_cast<void**>(executor.Receive()));
if (executor == NULL) {
LOG(WARNING) << "Failed to get an executor to get tab index.";
PostError(api_module_constants::kInternalErrorError);
return false;
}
hr = executor->GetTabIndex(reinterpret_cast<CeeeWindowHandle>(tab_window),
&index);
if (FAILED(hr)) {
LOG(ERROR) << "Failed to get tab info for tab: " << std::hex << tab_id <<
". " << com::LogHr(hr);
PostError(api_module_constants::kInternalErrorError);
return false;
}
}
result->SetInteger(ext::kIndexKey, static_cast<int>(index));
result->SetBoolean(ext::kIncognitoKey, ie_util::GetIEIsInPrivateBrowsing());
if (value_ == NULL) {
value_.reset(result.release());
} else {
DCHECK(value_->IsType(Value::TYPE_LIST));
ListValue* list = reinterpret_cast<ListValue*>(value_.get());
list->Append(result.release());
}
return true;
}
HRESULT TabApiResult::IsTabFromSameOrUnspecifiedFrameWindow(
const DictionaryValue& input_dict,
const Value* saved_window_value,
HWND* tab_window,
ApiDispatcher* dispatcher) {
int tab_id = 0;
bool success = input_dict.GetInteger(ext::kIdKey, &tab_id);
DCHECK(success && tab_id != 0) << "The input_dict MUST have a tab ID!!!";
DCHECK(dispatcher != NULL);
if (!dispatcher->IsTabIdValid(tab_id)) {
// This can happen if the tab died before we get here.
LOG(WARNING) << "Tab ID: " << tab_id << ", not recognized.";
return E_UNEXPECTED;
}
HWND input_tab_window = dispatcher->GetTabHandleFromId(tab_id);
if (tab_window != NULL)
*tab_window = input_tab_window;
if (saved_window_value == NULL)
return S_OK;
DCHECK(saved_window_value->IsType(Value::TYPE_INTEGER));
int saved_window_id = 0;
success = saved_window_value->GetAsInteger(&saved_window_id);
DCHECK(success && saved_window_id != 0);
HWND frame_window = NULL;
int frame_window_id = 0;
if (!input_dict.GetInteger(ext::kWindowIdKey, &frame_window_id)) {
// If the parent window is not specified, it is easy to fetch it ourselves.
frame_window = window_utils::GetTopLevelParent(input_tab_window);
frame_window_id = dispatcher->GetWindowIdFromHandle(frame_window);
DCHECK_NE(0, frame_window_id);
} else {
frame_window = dispatcher->GetWindowHandleFromId(frame_window_id);
DCHECK_EQ(window_utils::GetTopLevelParent(input_tab_window), frame_window);
}
return frame_window_id == saved_window_id ? S_OK : S_FALSE;
}
bool GetIntegerFromValue(
const Value& value, const char* key_name, int* out_value) {
switch (value.GetType()) {
case Value::TYPE_INTEGER: {
return value.GetAsInteger(out_value);
}
case Value::TYPE_DICTIONARY: {
const DictionaryValue* dict = static_cast<const DictionaryValue*>(&value);
if (dict->HasKey(key_name))
return dict->GetInteger(key_name, out_value);
*out_value = 0;
return true;
}
case Value::TYPE_LIST: {
const ListValue* args_list = static_cast<const ListValue*>(&value);
Value* anonymous_value = NULL;
if (!args_list->Get(0, &anonymous_value)) {
// If given an empty list value, we return 0 so that the frame window is
// fetched.
*out_value = 0;
return true;
}
DCHECK(anonymous_value != NULL);
return GetIntegerFromValue(*anonymous_value, key_name, out_value);
}
case Value::TYPE_NULL: {
// If given an empty list value, we return 0 so that the frame window is
// fetched.
*out_value = 0;
return true;
}
default: {
return false;
}
}
}
HWND TabApiResult::GetSpecifiedOrCurrentFrameWindow(const Value& args,
bool* specified) {
int window_id = 0;
if (!GetIntegerFromValue(args, ext::kWindowIdKey, &window_id)) {
NOTREACHED() << "Invalid Arguments.";
return NULL;
}
HWND frame_window = NULL;
ApiDispatcher* dispatcher = GetDispatcher();
DCHECK(dispatcher != NULL);
if (window_id != 0)
frame_window = dispatcher->GetWindowHandleFromId(window_id);
if (!frame_window) {
// TODO(mad@chromium.org): We currently don't have access to the
// actual 'current' window from the point of view of the extension
// API caller. Use one of the top windows for now. bb2255140
window_utils::FindDescendentWindow(NULL, windows::kIeFrameWindowClass,
true, &frame_window);
if (specified != NULL)
*specified = false;
} else {
if (specified != NULL)
*specified = true;
}
if (!frame_window) {
return NULL;
}
if (!window_utils::IsWindowClass(frame_window, windows::kIeFrameWindowClass))
return NULL;
return frame_window;
}
void GetTab::Execute(const ListValue& args, int request_id) {
scoped_ptr<TabApiResult> result(CreateApiResult(request_id));
int tab_id = kInvalidChromeSessionId;
if (!args.GetInteger(0, &tab_id)) {
result->PostError(api_module_constants::kInvalidArgumentsError);
return;
}
ApiDispatcher* dispatcher = GetDispatcher();
DCHECK(dispatcher != NULL);
if (!dispatcher->IsTabIdValid(tab_id)) {
result->PostError(ExtensionErrorUtils::FormatErrorMessage(
ext::kTabNotFoundError, base::IntToString(tab_id)));
return;
}
HWND tab_window = dispatcher->GetTabHandleFromId(tab_id);
if (!result->IsTabWindowClass(tab_window)) {
result->PostError(ExtensionErrorUtils::FormatErrorMessage(
ext::kTabNotFoundError, base::IntToString(tab_id)));
return;
}
// -1 when we don't know the index.
if (result->CreateTabValue(tab_id, -1)) {
// CreateTabValue called PostError if it returned false.
result->PostResult();
}
}
void GetCurrentTab::Execute(const ListValue& args, int request_id,
const DictionaryValue* associated_tab) {
// TODO(cindylau@chromium.org): This implementation of chrome.tabs.getCurrent
// assumes that the associated tab will be that of a tool band, since that is
// the only way we currently support running extension code in a tab context.
// If the way we associate tool bands to IE tabs/windows changes, and/or if
// we add other tab-related extension widgets (e.g. infobars, or directly
// loading extension pages in host browser tabs), we will need to revisit
// this implementation.
scoped_ptr<TabApiResult> result(CreateApiResult(request_id));
if (associated_tab == NULL) {
// The associated tab may validly be NULL, for instance if the API call
// originated from the background page.
result->PostResult();
return;
}
int tool_band_id;
if (!associated_tab->GetInteger(ext::kIdKey, &tool_band_id)) {
result->PostError(api_module_constants::kInternalErrorError);
return;
}
ApiDispatcher* dispatcher = GetDispatcher();
DCHECK(dispatcher != NULL);
HWND tab_window = dispatcher->GetTabHandleFromToolBandId(tool_band_id);
int tab_id = dispatcher->GetTabIdFromHandle(tab_window);
if (!result->IsTabWindowClass(tab_window)) {
result->PostError(ExtensionErrorUtils::FormatErrorMessage(
ext::kTabNotFoundError, base::IntToString(tab_id)));
return;
}
if (result->CreateTabValue(tab_id, -1))
result->PostResult();
}
void GetSelectedTab::Execute(const ListValue& args, int request_id) {
scoped_ptr<TabApiResult> result(CreateApiResult(request_id));
bool specified = false;
HWND frame_window = result->GetSpecifiedOrCurrentFrameWindow(args,
&specified);
if (!frame_window) {
result->PostError(ext::kNoCurrentWindowError);
return;
}
// The selected tab is the only visible "TabWindowClass" window
// that is a child of the frame window. Enumerate child windows to find it,
// and fill in the value_ when we do.
HWND selected_tab = NULL;
ApiDispatcher* dispatcher = GetDispatcher();
DCHECK(dispatcher != NULL);
if (!window_utils::FindDescendentWindow(
frame_window, windows::kIeTabWindowClass, true, &selected_tab) ||
!ExecutorsManager::IsKnownWindow(selected_tab)) {
if (specified) {
int frame_window_id = dispatcher->GetWindowIdFromHandle(frame_window);
// We remember the frame window if it was specified so that we only
// react asynchronously to new tabs created in the same frame window.
result->SetValue(ext::kWindowIdKey,
Value::CreateIntegerValue(frame_window_id));
}
DCHECK(dispatcher != NULL);
dispatcher->RegisterEphemeralEventHandler(
ext_event_names::kOnTabCreated,
GetSelectedTab::ContinueExecution,
// We don't want to destroy the result in the scoped_ptr when we pass
// it as user_data to GetSelectedTab::ContinueExecution().
result.release());
} else {
int tab_id = dispatcher->GetTabIdFromHandle(selected_tab);
DCHECK(tab_id != kInvalidChromeSessionId);
if (result->CreateTabValue(tab_id, -1))
result->PostResult();
}
}
HRESULT GetSelectedTab::ContinueExecution(
const std::string& input_args,
ApiDispatcher::InvocationResult* user_data,
ApiDispatcher* dispatcher) {
DCHECK(dispatcher != NULL);
DCHECK(user_data != NULL);
// Any tab is good for us, so relaunch the search for a selected tab
// by using the frame window of the newly created tab.
scoped_ptr<TabApiResult> result(static_cast<TabApiResult*>(user_data));
scoped_ptr<ListValue> args_list;
DictionaryValue* input_dict =
api_module_util::GetListAndDictionaryValue(input_args, &args_list);
if (input_dict == NULL) {
DCHECK(false) << "Event arguments are not a list with a dictionary in it.";
result->PostError(api_module_constants::kInternalErrorError);
return E_INVALIDARG;
}
HWND tab_window = NULL;
HRESULT hr = TabApiResult::IsTabFromSameOrUnspecifiedFrameWindow(
*input_dict, result->GetValue(ext::kWindowIdKey), &tab_window,
dispatcher);
if (FAILED(hr)) {
// The ApiDispatcher will forget about us and result's destructor will
// free the allocation of user_data.
result->PostError("Internal error while trying to finish tab selection.");
return hr;
}
if (hr == S_FALSE) {
// These are not the droids you are looking for. :-)
result.release(); // The ApiDispatcher will keep it alive.
return S_FALSE;
}
// We must reset the value and start from scratch in CreateTabValue.
// TODO(mad@chromium.org): We might be able to save a few steps if
// we support adding to existing value... Maybe...
int tab_id = dispatcher->GetTabIdFromHandle(tab_window);
DCHECK(tab_id != kInvalidChromeSessionId);
result->set_value(NULL);
if (result->CreateTabValue(tab_id, -1))
result->PostResult();
return S_OK;
}
bool GetAllTabsInWindowResult::Execute(BSTR tab_handles) {
// This is a list of tab_handles as it comes from the executor, not Chrome.
DCHECK(tab_handles);
scoped_ptr<ListValue> tabs_list;
if (!api_module_util::GetListFromJsonString(CW2A(tab_handles).m_psz,
&tabs_list)) {
NOTREACHED() << "Invalid tabs list BSTR: " << tab_handles;
PostError(api_module_constants::kInternalErrorError);
return false;
}
size_t num_values = tabs_list->GetSize();
if (num_values % 2 != 0) {
// Values should come in pairs, one for the handle and another one for the
// index.
NOTREACHED() << "Invalid tabs list BSTR: " << tab_handles;
PostError(api_module_constants::kInternalErrorError);
return false;
}
ApiDispatcher* dispatcher = GetDispatcher();
DCHECK(dispatcher != NULL);
// This will get populated by the calls to CreateTabValue in the loop below.
value_.reset(new ListValue());
num_values /= 2;
for (size_t index = 0; index < num_values; ++index) {
int tab_value = 0;
tabs_list->GetInteger(index * 2, &tab_value);
int tab_index = -1;
tabs_list->GetInteger(index * 2 + 1, &tab_index);
HWND tab_handle = reinterpret_cast<HWND>(tab_value);
if (!ExecutorsManager::IsKnownWindow(tab_handle))
continue;
int tab_id = dispatcher->GetTabIdFromHandle(tab_handle);
DCHECK(tab_id != kInvalidChromeSessionId);
if (!CreateTabValue(tab_id, tab_index)) {
return false;
}
}
return true;
}
void GetAllTabsInWindow::Execute(const ListValue& args, int request_id) {
scoped_ptr<GetAllTabsInWindowResult> result(CreateApiResult(request_id));
HWND frame_window = result->GetSpecifiedOrCurrentFrameWindow(args, NULL);
if (!frame_window) {
result->PostError(ext::kNoCurrentWindowError);
return;
}
ApiDispatcher* dispatcher = GetDispatcher();
DCHECK(dispatcher != NULL);
base::win::ScopedComPtr<ICeeeWindowExecutor> executor;
dispatcher->GetExecutor(frame_window, IID_ICeeeWindowExecutor,
reinterpret_cast<void**>(executor.Receive()));
if (executor == NULL) {
LOG(WARNING) << "Failed to get an executor to get list of tabs.";
result->PostError("Internal Error while getting all tabs in window.");
return;
}
long num_tabs = 0;
base::win::ScopedBstr tab_handles;
HRESULT hr = executor->GetTabs(tab_handles.Receive());
if (FAILED(hr)) {
DCHECK(tab_handles == NULL);
LOG(ERROR) << "Failed to get list of tabs for window: " << std::hex <<
frame_window << ". " << com::LogHr(hr);
result->PostError("Internal Error while getting all tabs in window.");
return;
}
// Execute posted an error if it returns false.
if (result->Execute(tab_handles))
result->PostResult();
}
void UpdateTab::Execute(const ListValue& args, int request_id) {
scoped_ptr<TabApiResult> result(CreateApiResult(request_id));
int tab_id = 0;
if (!args.GetInteger(0, &tab_id)) {
result->PostError(api_module_constants::kInvalidArgumentsError);
return;
}
ApiDispatcher* dispatcher = GetDispatcher();
DCHECK(dispatcher != NULL);
if (!dispatcher->IsTabIdValid(tab_id)) {
result->PostError(ExtensionErrorUtils::FormatErrorMessage(
ext::kTabNotFoundError, base::IntToString(tab_id)));
return;
}
HWND tab_window = dispatcher->GetTabHandleFromId(tab_id);
if (!result->IsTabWindowClass(tab_window)) {
result->PostError(ExtensionErrorUtils::FormatErrorMessage(
ext::kTabNotFoundError, base::IntToString(tab_id)));
return;
}
if (window_utils::WindowHasNoThread(tab_window)) {
result->PostError(ExtensionErrorUtils::FormatErrorMessage(
ext::kTabNotFoundError, base::IntToString(tab_id)));
return;
}
DictionaryValue* update_props = NULL;
if (!args.GetDictionary(1, &update_props)) {
result->PostError(api_module_constants::kInvalidArgumentsError);
return;
}
if (update_props->HasKey(ext::kUrlKey)) {
std::wstring url;
if (!update_props->GetString(ext::kUrlKey, &url)) {
result->PostError(api_module_constants::kInvalidArgumentsError);
return;
}
base::win::ScopedComPtr<ICeeeTabExecutor> executor;
dispatcher->GetExecutor(tab_window, IID_ICeeeTabExecutor,
reinterpret_cast<void**>(executor.Receive()));
if (executor == NULL) {
LOG(WARNING) << "Failed to get an executor to navigate tab.";
result->PostError("Internal error trying to update tab.");
return;
}
HRESULT hr = executor->Navigate(base::win::ScopedBstr(url.c_str()), 0,
base::win::ScopedBstr(L"_top"));
// Don't DCHECK here, see the comment at the bottom of
// CeeeExecutor::Navigate().
if (FAILED(hr)) {
LOG(ERROR) << "Failed to navigate tab: " << std::hex << tab_id <<
" to " << url << ". " << com::LogHr(hr);
result->PostError("Internal error trying to update tab.");
return;
}
}
if (update_props->HasKey(ext::kSelectedKey)) {
bool selected = false;
if (!update_props->GetBoolean(ext::kSelectedKey, &selected)) {
result->PostError(api_module_constants::kInvalidArgumentsError);
return;
}
// We only take action if the user wants to select the tab; this function
// does not actually let you deselect a tab.
if (selected) {
base::win::ScopedComPtr<ICeeeWindowExecutor> frame_executor;
dispatcher->GetExecutor(
window_utils::GetTopLevelParent(tab_window), IID_ICeeeWindowExecutor,
reinterpret_cast<void**>(frame_executor.Receive()));
if (frame_executor == NULL) {
LOG(WARNING) << "Failed to get a frame executor to select tab.";
result->PostError("Internal error trying to select tab.");
return;
}
HRESULT hr = frame_executor->SelectTab(
reinterpret_cast<CeeeWindowHandle>(tab_window));
if (FAILED(hr)) {
LOG(ERROR) << "Failed to select tab: " << std::hex << tab_id << ". " <<
com::LogHr(hr);
result->PostError("Internal error trying to select tab.");
return;
}
}
}
// TODO(mad@chromium.org): Check if we need to wait for the
// tabs.onUpdated event to make sure that the update was fully
// completed (e.g., Navigate above is async).
if (result->CreateTabValue(tab_id, -1))
result->PostResult();
}
void RemoveTab::Execute(const ListValue& args, int request_id) {
scoped_ptr<TabApiResult> result(CreateApiResult(request_id));
int tab_id;
if (!args.GetInteger(0, &tab_id)) {
result->PostError(api_module_constants::kInvalidArgumentsError);
return;
}
ApiDispatcher* dispatcher = GetDispatcher();
DCHECK(dispatcher != NULL);
if (!dispatcher->IsTabIdValid(tab_id)) {
result->PostError(ExtensionErrorUtils::FormatErrorMessage(
ext::kTabNotFoundError, base::IntToString(tab_id)));
return;
}
HWND tab_window = dispatcher->GetTabHandleFromId(tab_id);
if (!result->IsTabWindowClass(tab_window)) {
result->PostError(ExtensionErrorUtils::FormatErrorMessage(
ext::kTabNotFoundError, base::IntToString(tab_id)));
return;
}
base::win::ScopedComPtr<ICeeeWindowExecutor> frame_executor;
dispatcher->GetExecutor(window_utils::GetTopLevelParent(tab_window),
IID_ICeeeWindowExecutor,
reinterpret_cast<void**>(frame_executor.Receive()));
if (frame_executor == NULL) {
LOG(WARNING) << "Failed to get a frame executor to select tab.";
result->PostError("Internal error trying to select tab.");
return;
}
HRESULT hr = frame_executor->RemoveTab(
reinterpret_cast<CeeeWindowHandle>(tab_window));
if (FAILED(hr)) {
LOG(ERROR) << "Failed to remove tab: " << std::hex << tab_id << ". " <<
com::LogHr(hr);
result->PostError("Internal error trying to remove tab.");
return;
}
// Now we must wait for the tab removal to be completely done before
// posting the response back to Chrome Frame.
// And we remember the tab identifier so that we can recognize the event.
result->SetValue(ext::kTabIdKey, Value::CreateIntegerValue(tab_id));
dispatcher->RegisterEphemeralEventHandler(ext_event_names::kOnTabRemoved,
RemoveTab::ContinueExecution,
result.release());
}
HRESULT RemoveTab::ContinueExecution(const std::string& input_args,
ApiDispatcher::InvocationResult* user_data,
ApiDispatcher* dispatcher) {
DCHECK(user_data != NULL);
DCHECK(dispatcher != NULL);
scoped_ptr<TabApiResult> result(static_cast<TabApiResult*>(user_data));
scoped_ptr<ListValue> args_list;
int tab_id = 0;
if (!api_module_util::GetListAndIntegerValue(input_args, &args_list,
&tab_id)) {
NOTREACHED() << "Event arguments are not a list with an integer in it.";
result->PostError(api_module_constants::kInternalErrorError);
return E_INVALIDARG;
}
const Value* saved_tab_value = result->GetValue(ext::kTabIdKey);
DCHECK(saved_tab_value != NULL &&
saved_tab_value->IsType(Value::TYPE_INTEGER));
int saved_tab_id = 0;
bool success = saved_tab_value->GetAsInteger(&saved_tab_id);
DCHECK(success && saved_tab_id != 0);
if (saved_tab_id == tab_id) {
// The tabs.remove callback doesn't have any arguments.
result->set_value(NULL);
result->PostResult();
return S_OK;
} else {
// release doesn't destroy result, we need to keep it for next try.
result.release();
return S_FALSE; // S_FALSE keeps us in the queue.
}
}
void CreateTab::Execute(const ListValue& args, int request_id) {
// TODO(joi@chromium.org) Handle setting remaining tab properties
// ('title' and 'favIconUrl') if/when CE adds them (this is per a
// TODO for rafaelw@chromium.org in the extensions code).
scoped_ptr<TabApiResult> result(CreateApiResult(request_id));
DictionaryValue* input_dict = NULL;
if (!args.GetDictionary(0, &input_dict)) {
result->PostError(api_module_constants::kInvalidArgumentsError);
return;
}
bool specified = false;
HWND frame_window = result->GetSpecifiedOrCurrentFrameWindow(*input_dict,
&specified);
if (!frame_window) {
result->PostError(ext::kNoCurrentWindowError);
return;
}
ApiDispatcher* dispatcher = GetDispatcher();
DCHECK(dispatcher != NULL);
// In case the frame window wasn't specified, we must remember it for later
// use when we react to events below.
if (specified) {
int frame_window_id = dispatcher->GetWindowIdFromHandle(frame_window);
result->SetValue(
ext::kWindowIdKey, Value::CreateIntegerValue(frame_window_id));
}
std::string url_string(chrome::kAboutBlankURL); // default if no URL provided
if (input_dict->HasKey(ext::kUrlKey)) {
if (!input_dict->GetString(ext::kUrlKey, &url_string)) {
result->PostError(api_module_constants::kInvalidArgumentsError);
return;
}
GURL url(url_string);
if (!url.is_valid()) {
// TODO(joi@chromium.org) See if we can support absolute paths in IE (see
// extension_tabs_module.cc, AbsolutePath function and its uses)
result->PostError(ExtensionErrorUtils::FormatErrorMessage(
ext::kInvalidUrlError, url_string));
return;
}
// Remember the URL, we will use it to recognize the event below.
result->SetValue(ext::kUrlKey, Value::CreateStringValue(url_string));
}
bool selected = true;
if (input_dict->HasKey(ext::kSelectedKey)) {
if (!input_dict->GetBoolean(ext::kSelectedKey, &selected)) {
result->PostError(api_module_constants::kInvalidArgumentsError);
return;
}
}
if (input_dict->HasKey(ext::kIndexKey)) {
int index = -1;
if (!input_dict->GetInteger(ext::kIndexKey, &index)) {
result->PostError(api_module_constants::kInvalidArgumentsError);
return;
}
result->SetValue(ext::kIndexKey, Value::CreateIntegerValue(index));
}
// We will have some work pending, even after we completed the tab creation,
// because the tab creation itself is asynchronous and we must wait for it
// to complete before we can post the complete result.
// UNFORTUNATELY, this scheme doesn't work in protected mode for some reason.
// So bb2284073 & bb2492252 might still occur there.
std::wstring url_wstring = UTF8ToWide(url_string);
if (base::win::GetVersion() < base::win::VERSION_VISTA) {
base::win::ScopedComPtr<IWebBrowser2> browser;
HRESULT hr = ie_util::GetWebBrowserForTopLevelIeHwnd(
frame_window, NULL, browser.Receive());
DCHECK(SUCCEEDED(hr)) << "Can't get the browser for window: " <<
frame_window;
if (FAILED(hr)) {
result->PostError(api_module_constants::kInternalErrorError);
return;
}
long flags = selected ? navOpenInNewTab : navOpenInBackgroundTab;
hr = browser->Navigate(
base::win::ScopedBstr(url_wstring.c_str()),
const_cast<VARIANT*>(&base::win::ScopedVariant(flags)),
const_cast<VARIANT*>(&base::win::ScopedVariant(L"_blank")),
const_cast<VARIANT*>(&base::win::ScopedVariant()), // Post data
const_cast<VARIANT*>(&base::win::ScopedVariant())); // Headers
DCHECK(SUCCEEDED(hr)) << "Failed to create tab. " << com::LogHr(hr);
if (FAILED(hr)) {
result->PostError("Internal error while trying to create tab.");
return;
}
} else {
// To create a new tab, we find an existing tab in the desired window (there
// is always at least one), and use it to navigate to a new tab.
HWND existing_tab = ExecutorsManager::FindTabChild(frame_window);
DCHECK(existing_tab != NULL) << "Can't find an existing tab for" <<
frame_window;
if (existing_tab == NULL) {
result->PostError("Internal error while trying to create tab.");
return;
}
base::win::ScopedComPtr<ICeeeTabExecutor> executor;
dispatcher->GetExecutor(existing_tab, IID_ICeeeTabExecutor,
reinterpret_cast<void**>(executor.Receive()));
if (executor == NULL) {
LOG(WARNING) << "Failed to get an executor to create a tab.";
result->PostError("Internal error while trying to create tab.");
return;
}
long flags = selected ? navOpenInNewTab : navOpenInBackgroundTab;
HRESULT hr = executor->Navigate(base::win::ScopedBstr(url_wstring.c_str()),
flags, base::win::ScopedBstr(L"_blank"));
if (FAILED(hr)) {
// Log the error without DCHECKING There are legit reasons for Navigate
// to fail, as explained in comments in CeeeExecutor::Navigate.
// TODO(motek@chromium.org) See why exactly we fail here in some
// integration tests.
LOG(ERROR) << "Failed to create tab. " << com::LogHr(hr);
result->PostError("Internal error while trying to create tab.");
return;
}
}
// And now we must wait for the new tab to be created before we can respond.
dispatcher->RegisterEphemeralEventHandler(
ext_event_names::kOnTabCreated,
CreateTab::ContinueExecution,
// We don't want to destroy the result in the scoped_ptr when we pass
// it as user_data to CreateTab::ContinueExecution().
result.release());
}
HRESULT CreateTab::ContinueExecution(const std::string& input_args,
ApiDispatcher::InvocationResult* user_data,
ApiDispatcher* dispatcher) {
DCHECK(user_data != NULL);
DCHECK(dispatcher != NULL);
scoped_ptr<TabApiResult> result(static_cast<TabApiResult*>(user_data));
// Check if it has been created with the same info we were created for.
scoped_ptr<ListValue> args_list;
DictionaryValue* input_dict =
api_module_util::GetListAndDictionaryValue(input_args, &args_list);
if (input_dict == NULL) {
DCHECK(false) << "Event arguments are not a list with a dictionary in it.";
result->PostError(api_module_constants::kInvalidArgumentsError);
return E_INVALIDARG;
}
HWND tab_window = NULL;
HRESULT hr = TabApiResult::IsTabFromSameOrUnspecifiedFrameWindow(
*input_dict, result->GetValue(ext::kWindowIdKey), &tab_window,
dispatcher);
if (FAILED(hr)) {
// The ApiDispatcher will forget about us and result's destructor will
// free the allocation of user_data.
result->PostError("Internal error while trying to finish tab creation.");
return hr;
}
if (hr == S_FALSE) {
// These are not the droids you are looking for. :-)
result.release(); // The ApiDispatcher will keep it alive.
return S_FALSE;
}
std::string event_url;
bool success = input_dict->GetString(ext::kUrlKey, &event_url);
DCHECK(success) << "The event MUST send a URL!!!";
// if we didn't specify a URL, we should have navigated to about blank.
std::string requested_url(chrome::kAboutBlankURL);
// Ignore failures here, we fall back to the default about blank.
const Value* url_value = result->GetValue(ext::kUrlKey);
DCHECK(url_value != NULL && url_value->IsType(Value::TYPE_STRING));
if (url_value != NULL && url_value->IsType(Value::TYPE_STRING)) {
bool success = url_value->GetAsString(&requested_url);
DCHECK(success) << "url_value->GetAsString() Failed!";
}
if (GURL(event_url) != GURL(requested_url)) {
result.release(); // The ApiDispatcher will keep it alive.
return S_FALSE;
}
// We can't rely on selected, since it may have changed if
// another tab creation was made before we got to broadcast the completion
// of this one, so we will assume this one is ours.
// Now move the tab to desired index if specified, we couldn't do it until we
// had a tab_id.
long destination_index = -1;
const Value* index_value = result->GetValue(ext::kIndexKey);
if (index_value != NULL) {
DCHECK(index_value->IsType(Value::TYPE_INTEGER));
int destination_index_int = -1;
bool success = index_value->GetAsInteger(&destination_index_int);
DCHECK(success) << "index_value->GetAsInteger()";
HWND frame_window = window_utils::GetTopLevelParent(tab_window);
base::win::ScopedComPtr<ICeeeWindowExecutor> frame_executor;
dispatcher->GetExecutor(frame_window, __uuidof(ICeeeWindowExecutor),
reinterpret_cast<void**>(frame_executor.Receive()));
if (frame_executor == NULL) {
LOG(WARNING) << "Failed to get an executor for the frame.";
result->PostError("Internal error while trying to move created tab.");
return E_UNEXPECTED;
}
destination_index = static_cast<long>(destination_index_int);
HRESULT hr = frame_executor->MoveTab(
reinterpret_cast<CeeeWindowHandle>(tab_window), destination_index);
if (FAILED(hr)) {
LOG(ERROR) << "Failed to move tab: " << std::hex << tab_window << ". " <<
com::LogHr(hr);
result->PostError("Internal error while trying to move created tab.");
return E_UNEXPECTED;
}
}
// We must reset current state before calling CreateTabValue.
result->set_value(NULL);
// TODO(mad@chromium.org): Do we need to go through CreateTabValue?
// Maybe we already have enough info available to create the
// response???
int tab_id = dispatcher->GetTabIdFromHandle(tab_window);
DCHECK(tab_id != kInvalidChromeSessionId);
if (result->CreateTabValue(tab_id, destination_index))
result->PostResult();
return S_OK;
}
bool CreateTab::EventHandler(const std::string& input_args,
std::string* converted_args,
ApiDispatcher* dispatcher) {
DCHECK(converted_args);
*converted_args = input_args;
scoped_ptr<ListValue> input_list;
DictionaryValue* input_dict =
api_module_util::GetListAndDictionaryValue(input_args, &input_list);
if (input_dict == NULL) {
DCHECK(false) << "Input arguments are not a list with a dictionary in it.";
return false;
}
// Check if we got the index, this would mean we already have all we need.
int int_value = -1;
if (input_dict->GetInteger(ext::kIndexKey, &int_value)) {
// We should also have all other non-optional values
DCHECK(input_dict->GetInteger(ext::kWindowIdKey, &int_value));
bool bool_value = false;
DCHECK(input_dict->GetBoolean(ext::kSelectedKey, &bool_value));
return false;
}
// Get the complete tab info from the tab_handle coming from IE.
// Yes, this is actually a tab handle and not an ID that's in the dict.
int tab_handle = reinterpret_cast<int>(INVALID_HANDLE_VALUE);
bool success = input_dict->GetInteger(ext::kIdKey, &tab_handle);
DCHECK(success) << "Couldn't get the tab ID key from the input args.";
int tab_id = dispatcher->GetTabIdFromHandle(
reinterpret_cast<HWND>(tab_handle));
DCHECK(tab_id != kInvalidChromeSessionId);
TabApiResult result(TabApiResult::kNoRequestId);
if (result.CreateTabValue(tab_id, -1)) {
input_list->Set(0, result.value()->DeepCopy());
base::JSONWriter::Write(input_list.get(), false, converted_args);
return true;
} else {
// Don't DCHECK, this can happen if we close the window while tabs are
// being created.
// TODO(mad@chromium.org): Find a way to DCHECK that the window is
// actually closing.
return false;
}
}
void MoveTab::Execute(const ListValue& args, int request_id) {
scoped_ptr<TabApiResult> result(CreateApiResult(request_id));
int tab_id = 0;
if (!args.GetInteger(0, &tab_id)) {
result->PostError(api_module_constants::kInvalidArgumentsError);
return;
}
ApiDispatcher* dispatcher = GetDispatcher();
DCHECK(dispatcher != NULL);
if (!dispatcher->IsTabIdValid(tab_id)) {
result->PostError(ExtensionErrorUtils::FormatErrorMessage(
ext::kTabNotFoundError, base::IntToString(tab_id)));
return;
}
HWND tab_window = dispatcher->GetTabHandleFromId(tab_id);
if (!result->IsTabWindowClass(tab_window)) {
result->PostError(ExtensionErrorUtils::FormatErrorMessage(
ext::kTabNotFoundError, base::IntToString(tab_id)));
return;
}
DictionaryValue* update_props = NULL;
if (!args.GetDictionary(1, &update_props)) {
NOTREACHED() << "Can't get update properties from dictionary argument";
result->PostError(api_module_constants::kInvalidArgumentsError);
return;
}
if (update_props->HasKey(ext::kWindowIdKey)) {
// TODO(joi@chromium.org) Move to shared constants file
result->PostError("Moving tabs between windows is not supported.");
return;
}
int new_index = -1;
if (!update_props->GetInteger(ext::kIndexKey, &new_index)) {
NOTREACHED() << "Can't get tab index from update properties.";
result->PostError(api_module_constants::kInvalidArgumentsError);
return;
}
HWND frame_window = window_utils::GetTopLevelParent(tab_window);
base::win::ScopedComPtr<ICeeeWindowExecutor> frame_executor;
dispatcher->GetExecutor(frame_window, IID_ICeeeWindowExecutor,
reinterpret_cast<void**>(frame_executor.Receive()));
if (frame_executor == NULL) {
LOG(WARNING) << "Failed to get an executor for the frame.";
result->PostError("Internal Error while trying to move tab.");
return;
}
HRESULT hr = frame_executor->MoveTab(
reinterpret_cast<CeeeWindowHandle>(tab_window), new_index);
if (FAILED(hr)) {
LOG(ERROR) << "Failed to move tab: " << std::hex << tab_id << ". " <<
com::LogHr(hr);
result->PostError("Internal Error while trying to move tab.");
return;
}
if (result->CreateTabValue(tab_id, new_index))
result->PostResult();
}
ApiDispatcher::InvocationResult* TabsInsertCode::ExecuteImpl(
const ListValue& args,
int request_id,
CeeeTabCodeType type,
int* tab_id,
HRESULT* hr) {
scoped_ptr<ApiDispatcher::InvocationResult> result(
CreateApiResult(request_id));
// TODO(ericdingle@chromium.org): This needs to support when NULL is
// sent in as the first parameter.
if (!args.GetInteger(0, tab_id)) {
result->PostError(api_module_constants::kInvalidArgumentsError);
return NULL;
}
DictionaryValue* dict;
if (!args.GetDictionary(1, &dict)) {
result->PostError(api_module_constants::kInvalidArgumentsError);
return NULL;
}
// The dictionary should have either a code property or a file property,
// but not both.
std::string code;
std::string file;
if (dict->HasKey(ext::kCodeKey) && dict->HasKey(ext::kFileKey)) {
result->PostError(ext::kMoreThanOneValuesError);
return NULL;
} else if (dict->HasKey(ext::kCodeKey)) {
dict->GetString(ext::kCodeKey, &code);
} else if (dict->HasKey(ext::kFileKey)) {
dict->GetString(ext::kFileKey, &file);
} else {
result->PostError(ext::kNoCodeOrFileToExecuteError);
return NULL;
}
// All frames is optional. If not specified, the default value is false.
bool all_frames;
if (!dict->GetBoolean(ext::kAllFramesKey, &all_frames))
all_frames = false;
ApiDispatcher* dispatcher = GetDispatcher();
DCHECK(dispatcher != NULL);
if (!dispatcher->IsTabIdValid(*tab_id)) {
result->PostError(ExtensionErrorUtils::FormatErrorMessage(
ext::kTabNotFoundError, base::IntToString(*tab_id)));
return NULL;
}
HWND tab_window = dispatcher->GetTabHandleFromId(*tab_id);
if (!TabApiResult::IsTabWindowClass(tab_window)) {
result->PostError(ExtensionErrorUtils::FormatErrorMessage(
ext::kTabNotFoundError, base::IntToString(*tab_id)));
return NULL;
}
base::win::ScopedComPtr<ICeeeTabExecutor> tab_executor;
dispatcher->GetExecutor(tab_window, IID_ICeeeTabExecutor,
reinterpret_cast<void**>(tab_executor.Receive()));
if (tab_executor == NULL) {
LOG(WARNING) << "Failed to get an executor for the frame.";
result->PostError("Internal Error while trying to insert code in tab.");
return NULL;
}
*hr = tab_executor->InsertCode(
base::win::ScopedBstr(ASCIIToWide(code).c_str()),
base::win::ScopedBstr(ASCIIToWide(file).c_str()), all_frames, type);
return result.release();
}
void TabsExecuteScript::Execute(const ListValue& args, int request_id) {
int tab_id;
HRESULT hr = S_OK;
scoped_ptr<ApiDispatcher::InvocationResult> result(
TabsInsertCode::ExecuteImpl(
args, request_id, kCeeeTabCodeTypeJs, &tab_id, &hr));
if (result.get() == NULL)
return;
if (FAILED(hr)) {
LOG(ERROR) << "Failed to execute script in tab: " <<
std::hex <<
tab_id <<
". " <<
com::LogHr(hr);
result->PostError("Internal Error while trying to execute script in tab.");
} else {
result->PostResult();
}
}
void TabsInsertCSS::Execute(const ListValue& args, int request_id) {
int tab_id;
HRESULT hr = S_OK;
scoped_ptr<ApiDispatcher::InvocationResult> result(
TabsInsertCode::ExecuteImpl(
args, request_id, kCeeeTabCodeTypeCss, &tab_id, &hr));
if (result.get() == NULL)
return;
if (FAILED(hr)) {
LOG(ERROR) << "Failed to insert CSS in tab: " <<
std::hex <<
tab_id <<
". " <<
com::LogHr(hr);
result->PostError("Internal Error while trying to insert CSS in tab.");
} else {
result->PostResult();
}
}
TabInfo::TabInfo() {
url = NULL;
title = NULL;
status = kCeeeTabStatusLoading;
fav_icon_url = NULL;
protected_mode = FALSE;
}
TabInfo::~TabInfo() {
Clear();
}
void TabInfo::Clear() {
// SysFreeString accepts NULL pointers.
::SysFreeString(url);
url = NULL;
::SysFreeString(title);
title = NULL;
::SysFreeString(fav_icon_url);
fav_icon_url = NULL;
status = kCeeeTabStatusLoading;
protected_mode = FALSE;
}
} // namespace tab_api
|