FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
rstudio/src/cpp/session/SessionModuleContext.cpp at master · pearsonca/rstudio · GitHub
pearsonca
/
rstudio
Public
forked from
rstudio/rstudio
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
rstudio
/
src
/
cpp
/
session
/
SessionModuleContext.cpp
Copy path
More file actions
More file actions
Latest commit
History
History
History
2755 lines (2339 loc) · 75.4 KB
Breadcrumbs
rstudio
/
src
/
cpp
/
session
/
SessionModuleContext.cpp
Copy path
File metadata and controls
2755 lines (2339 loc) · 75.4 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
/*
* SessionModuleContext.cpp
*
* Copyright (C) 2009-20 by RStudio, PBC
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#
include
"
SessionModuleContextInternal.hpp
"
#
include
<
vector
>
#
include
<
boost/assert.hpp
>
#
include
<
boost/utility.hpp
>
#
include
<
boost/format.hpp
>
#
include
<
boost/numeric/conversion/cast.hpp
>
#
include
<
core/BoostSignals.hpp
>
#
include
<
core/BoostThread.hpp
>
#
include
<
shared_core/Error.hpp
>
#
include
<
shared_core/FilePath.hpp
>
#
include
<
core/FileInfo.hpp
>
#
include
<
core/Log.hpp
>
#
include
<
core/Base64.hpp
>
#
include
<
core/Hash.hpp
>
#
include
<
core/Settings.hpp
>
#
include
<
core/DateTime.hpp
>
#
include
<
core/FileSerializer.hpp
>
#
include
<
core/markdown/Markdown.hpp
>
#
include
<
core/system/FileScanner.hpp
>
#
include
<
core/IncrementalCommand.hpp
>
#
include
<
core/PeriodicCommand.hpp
>
#
include
<
core/collection/Tree.hpp
>
#
include
<
core/http/Util.hpp
>
#
include
<
core/system/Process.hpp
>
#
include
<
core/system/FileMonitor.hpp
>
#
include
<
core/system/FileChangeEvent.hpp
>
#
include
<
core/system/Environment.hpp
>
#
include
<
core/system/ShellUtils.hpp
>
#
include
<
core/system/Xdg.hpp
>
#
include
<
core/r_util/RPackageInfo.hpp
>
#
include
<
r/RSexp.hpp
>
#
include
<
r/RUtil.hpp
>
#
include
<
r/RExec.hpp
>
#
include
<
r/RRoutines.hpp
>
#
include
<
r/RJson.hpp
>
#
include
<
r/RJsonRpc.hpp
>
#
include
<
r/RSourceManager.hpp
>
#
include
<
r/RErrorCategory.hpp
>
#
include
<
r/RFunctionHook.hpp
>
#
include
<
r/session/RSession.hpp
>
#
include
<
r/session/RConsoleActions.hpp
>
#
include
<
session/SessionOptions.hpp
>
#
include
<
session/SessionPersistentState.hpp
>
#
include
<
session/SessionClientEvent.hpp
>
#
include
<
session/SessionClientEventService.hpp
>
#
include
<
session/http/SessionRequest.hpp
>
#
include
"
SessionClientEventQueue.hpp
"
#
include
<
session/projects/SessionProjects.hpp
>
#
include
<
session/SessionConstants.hpp
>
#
include
<
session/SessionContentUrls.hpp
>
#
include
<
session/prefs/UserPrefs.hpp
>
#
include
<
session/prefs/UserState.hpp
>
#
include
<
shared_core/system/User.hpp
>
#
include
"
modules/SessionBreakpoints.hpp
"
#
include
"
modules/SessionVCS.hpp
"
#
include
"
modules/SessionFiles.hpp
"
#
include
"
session-config.h
"
using
namespace
rstudio
::core
;
namespace
rstudio
{
namespace
session
{
namespace
module_context
{
namespace
{
//
simple service for handling console_input rpc requests
class
ConsoleInputService
: boost::noncopyable
{
public:
ConsoleInputService
()
{
core::thread::safeLaunchThread
(
boost::bind
(&ConsoleInputService::run,
this
),
&thread_);
}
~ConsoleInputService
()
{
enqueue
(
"
!
"
);
}
void
enqueue
(
const
std::string& input)
{
requests_.
enque
(input);
}
private:
void
run
()
{
while
(
true
)
{
std::string input;
while
(requests_.
deque
(&input))
{
if
(input ==
"
!
"
)
return
;
core::http::Response response;
Error error =
session::http::sendSessionRequest
(
"
/rpc/console_input
"
,
input,
&response);
if
(error)
LOG_ERROR
(error);
}
requests_.
wait
();
}
}
boost::thread thread_;
core::thread::ThreadsafeQueue<std::string> requests_;
};
ConsoleInputService&
consoleInputService
()
{
static
ConsoleInputService instance;
return
instance;
}
//
enqueClientEvent from R
SEXP
rs_enqueClientEvent
(
SEXP
nameSEXP,
SEXP
dataSEXP)
{
try
{
//
extract name
std::string name =
r::sexp::asString
(nameSEXP);
//
extract json value (for primitive types we only support scalars
//
since this is the most common type of event data). to return an
//
array of primitives you need to wrap them in a list/object
Error extractError ;
json::Value data ;
switch
(
TYPEOF
(dataSEXP))
{
case
NILSXP
:
{
//
do nothing, data will be a null json value
break
;
}
case
VECSXP
:
{
extractError =
r::json::jsonValueFromList
(dataSEXP, &data);
break
;
}
default
:
{
extractError =
r::json::jsonValueFromScalar
(dataSEXP, &data);
break
;
}
}
//
check for error
if
(extractError)
{
LOG_ERROR
(extractError);
throw
r::exec::RErrorException
(
"
Couldn't extract json value from event data
"
);
}
//
determine the event type from the event name
int
type = -
1
;
if
(name ==
"
package_status_changed
"
)
type = session::client_events::
kPackageStatusChanged
;
else
if
(name ==
"
unhandled_error
"
)
type = session::client_events::
kUnhandledError
;
else
if
(name ==
"
enable_rstudio_connect
"
)
type = session::client_events::
kEnableRStudioConnect
;
else
if
(name ==
"
shiny_gadget_dialog
"
)
type = session::client_events::
kShinyGadgetDialog
;
else
if
(name ==
"
rmd_params_ready
"
)
type = session::client_events::
kRmdParamsReady
;
else
if
(name ==
"
jump_to_function
"
)
type = session::client_events::
kJumpToFunction
;
else
if
(name ==
"
send_to_console
"
)
type = session::client_events::
kSendToConsole
;
else
if
(name ==
"
rprof_started
"
)
type = session::client_events::
kRprofStarted
;
else
if
(name ==
"
rprof_stopped
"
)
type = session::client_events::
kRprofStopped
;
else
if
(name ==
"
rprof_created
"
)
type = session::client_events::
kRprofCreated
;
else
if
(name ==
"
editor_command
"
)
type = session::client_events::
kEditorCommand
;
else
if
(name ==
"
navigate_shiny_frame
"
)
type = session::client_events::
kNavigateShinyFrame
;
else
if
(name ==
"
update_new_connection_dialog
"
)
type = session::client_events::
kUpdateNewConnectionDialog
;
else
if
(name ==
"
terminal_subprocs
"
)
type = session::client_events::
kTerminalSubprocs
;
else
if
(name ==
"
rstudioapi_show_dialog
"
)
type = session::client_events::
kRStudioAPIShowDialog
;
else
if
(name ==
"
object_explorer_event
"
)
type = session::client_events::
kObjectExplorerEvent
;
else
if
(name ==
"
send_to_terminal
"
)
type = session::client_events::
kSendToTerminal
;
else
if
(name ==
"
clear_terminal
"
)
type = session::client_events::
kClearTerminal
;
else
if
(name ==
"
add_terminal
"
)
type = session::client_events::
kAddTerminal
;
else
if
(name ==
"
activate_terminal
"
)
type = session::client_events::
kActivateTerminal
;
else
if
(name ==
"
terminal_cwd
"
)
type = session::client_events::
kTerminalCwd
;
else
if
(name ==
"
remove_terminal
"
)
type = session::client_events::
kRemoveTerminal
;
else
if
(name ==
"
show_page_viewer
"
)
type = session::client_events::
kShowPageViewerEvent
;
else
if
(name ==
"
data_output_completed
"
)
type = session::client_events::
kDataOutputCompleted
;
else
if
(name ==
"
new_document_with_code
"
)
type = session::client_events::
kNewDocumentWithCode
;
else
if
(name ==
"
available_packages_ready
"
)
type = session::client_events::
kAvailablePackagesReady
;
else
if
(name ==
"
compute_theme_colors
"
)
type = session::client_events::
kComputeThemeColors
;
else
if
(name ==
"
tutorial_command
"
)
type = session::client_events::
kTutorialCommand
;
else
if
(name ==
"
tutorial_launch
"
)
type = session::client_events::
kTutorialLaunch
;
if
(type != -
1
)
{
ClientEvent
event
(type, data);
session::clientEventQueue
().
add
(event);
}
else
{
LOG_ERROR_MESSAGE
(
"
Unexpected event name from R:
"
+ name);
}
}
catch
(r::exec::RErrorException& e)
{
r::exec::error
(e.
message
());
}
CATCH_UNEXPECTED_EXCEPTION
return
R_NilValue ;
}
SEXP
rs_activatePane
(
SEXP
paneSEXP)
{
module_context::activatePane
(
r::sexp::safeAsString
(paneSEXP));
return
R_NilValue;
}
//
show error message from R
SEXP
rs_showErrorMessage
(
SEXP
titleSEXP,
SEXP
messageSEXP)
{
std::string title =
r::sexp::asString
(titleSEXP);
std::string message =
r::sexp::asString
(messageSEXP);
module_context::showErrorMessage
(title, message);
return
R_NilValue;
}
//
log error message from R
SEXP
rs_logErrorMessage
(
SEXP
messageSEXP)
{
std::string message =
r::sexp::asString
(messageSEXP);
LOG_ERROR_MESSAGE
(message);
return
R_NilValue;
}
//
log warning message from R
SEXP
rs_logWarningMessage
(
SEXP
messageSEXP)
{
std::string message =
r::sexp::asString
(messageSEXP);
LOG_WARNING_MESSAGE
(message);
return
R_NilValue;
}
//
sleep the main thread (debugging function used to test rpc/abort)
SEXP
rs_threadSleep
(
SEXP
secondsSEXP)
{
int
seconds =
r::sexp::asInteger
(secondsSEXP);
boost::this_thread::sleep
(
boost::posix_time::seconds
(seconds));
return
R_NilValue;
}
//
get rstudio mode
SEXP
rs_rstudioProgramMode
()
{
r::sexp::Protect rProtect;
return
r::sexp::create
(
session::options
().
programMode
(), &rProtect);
}
//
get rstudio edition
SEXP
rs_rstudioEdition
()
{
return
R_NilValue;
}
//
get version
SEXP
rs_rstudioVersion
()
{
r::sexp::Protect rProtect;
return
r::sexp::create
(
std::string
(
RSTUDIO_VERSION
), &rProtect);
}
//
get release name
SEXP
rs_rstudioReleaseName
()
{
r::sexp::Protect rProtect;
return
r::sexp::create
(
std::string
(
RSTUDIO_RELEASE_NAME
), &rProtect);
}
//
get citation
SEXP
rs_rstudioCitation
()
{
FilePath resPath =
session::options
().
rResourcesPath
();
FilePath citationPath = resPath.
completeChildPath
(
"
CITATION
"
);
//
the citation file may not exist when working in e.g.
//
development configurations so just ignore if it's missing
if
(!citationPath.
exists
())
return
R_NilValue;
SEXP
citationSEXP;
r::sexp::Protect rProtect;
Error error =
r::exec::RFunction
(
"
utils:::readCitationFile
"
,
citationPath.
getAbsolutePath
())
.
call
(&citationSEXP,
&rProtect);
if
(error)
{
LOG_ERROR
(error);
return
R_NilValue;
}
else
{
return
citationSEXP;
}
}
SEXP
rs_setUsingMingwGcc49
(
SEXP
usingSEXP)
{
bool
usingMingwGcc49 =
r::sexp::asLogical
(usingSEXP);
prefs::userState
().
setUsingMingwGcc49
(usingMingwGcc49);
return
R_NilValue;
}
//
ensure file hidden
SEXP
rs_ensureFileHidden
(
SEXP
fileSEXP)
{
#
ifdef
_WIN32
std::string file =
r::sexp::asString
(fileSEXP);
if
(!file.
empty
())
{
FilePath filePath =
module_context::resolveAliasedPath
(file);
Error error =
core::system::makeFileHidden
(filePath);
if
(error)
LOG_ERROR
(error);
}
#
endif
return
R_NilValue;
}
SEXP
rs_sourceDiagnostics
()
{
module_context::sourceDiagnostics
();
return
R_NilValue;
}
SEXP
rs_packageLoaded
(
SEXP
pkgnameSEXP)
{
std::string pkgname =
r::sexp::safeAsString
(pkgnameSEXP);
//
fire server event
events
().
onPackageLoaded
(pkgname);
//
fire client event
ClientEvent
packageLoadedEvent
(
client_events::
kPackageLoaded
,
json::Value
(pkgname));
enqueClientEvent
(packageLoadedEvent);
return
R_NilValue;
}
SEXP
rs_packageUnloaded
(
SEXP
pkgnameSEXP)
{
std::string pkgname =
r::sexp::safeAsString
(pkgnameSEXP);
ClientEvent
packageUnloadedEvent
(
client_events::
kPackageUnloaded
,
json::Value
(pkgname));
enqueClientEvent
(packageUnloadedEvent);
return
R_NilValue;
}
SEXP
rs_userPrompt
(
SEXP
typeSEXP,
SEXP
captionSEXP,
SEXP
messageSEXP,
SEXP
yesLabelSEXP,
SEXP
noLabelSEXP,
SEXP
includeCancelSEXP,
SEXP
yesIsDefaultSEXP)
{
UserPrompt
prompt
(
r::sexp::asInteger
(typeSEXP),
r::sexp::safeAsString
(captionSEXP),
r::sexp::safeAsString
(messageSEXP),
r::sexp::safeAsString
(yesLabelSEXP),
r::sexp::safeAsString
(noLabelSEXP),
r::sexp::asLogical
(includeCancelSEXP),
r::sexp::asLogical
(yesIsDefaultSEXP));
UserPrompt::Response response =
showUserPrompt
(prompt);
r::sexp::Protect rProtect;
return
r::sexp::create
(response, &rProtect);
}
SEXP
rs_restartR
(
SEXP
afterRestartSEXP)
{
std::string afterRestart =
r::sexp::safeAsString
(afterRestartSEXP);
json::Object dataJson;
dataJson[
"
after_restart
"
] = afterRestart;
ClientEvent
event
(client_events::
kSuspendAndRestart
, dataJson);
module_context::enqueClientEvent
(event);
return
R_NilValue;
}
SEXP
rs_generateShortUuid
()
{
//
generate a short uuid -- we make this available in R code so that it's
//
possible to create random identifiers without perturbing the state of the
//
RNG that R uses
std::string uuid =
core::system::generateShortenedUuid
();
r::sexp::Protect rProtect;
return
r::sexp::create
(uuid, &rProtect);
}
SEXP
rs_markdownToHTML
(
SEXP
contentSEXP)
{
std::string content =
r::sexp::safeAsString
(contentSEXP);
std::string htmlContent;
Error error =
markdown::markdownToHTML
(content,
markdown::Extensions
(),
markdown::HTMLOptions
(),
&htmlContent);
if
(error)
{
LOG_ERROR
(error);
htmlContent = content;
}
r::sexp::Protect rProtect;
return
r::sexp::create
(htmlContent, &rProtect);
}
inline
std::string
persistantValueName
(
SEXP
nameSEXP)
{
return
"
rstudioapi_persistent_values_
"
+
r::sexp::safeAsString
(nameSEXP);
}
SEXP
rs_setPersistentValue
(
SEXP
nameSEXP,
SEXP
valueSEXP)
{
std::string name =
persistantValueName
(nameSEXP);
std::string value =
r::sexp::safeAsString
(valueSEXP);
persistentState
().
settings
().
set
(name, value);
return
R_NilValue;
}
SEXP
rs_getPersistentValue
(
SEXP
nameSEXP)
{
std::string name =
persistantValueName
(nameSEXP);
if
(
persistentState
().
settings
().
contains
(name))
{
std::string value =
persistentState
().
settings
().
get
(name);
r::sexp::Protect rProtect;
return
r::sexp::create
(value, &rProtect);
}
else
{
return
R_NilValue;
}
}
}
//
anonymous namespace
//
register a scratch path which is monitored
namespace
{
typedef
std::map<FilePath,OnFileChange> MonitoredScratchPaths;
MonitoredScratchPaths s_monitoredScratchPaths;
bool
s_monitorByScanning =
false
;
FilePath
monitoredParentPath
()
{
FilePath monitoredPath =
userScratchPath
().
completePath
(
kMonitoredPath
);
Error error = monitoredPath.
ensureDirectory
();
if
(error)
LOG_ERROR
(error);
return
monitoredPath;
}
bool
monitoredScratchFilter
(
const
FileInfo& fileInfo)
{
return
true
;
}
void
onFilesChanged
(
const
std::vector<core::system::FileChangeEvent>& changes)
{
for
(
const
core::system::FileChangeEvent& fileChange : changes)
{
FilePath
changedFilePath
(fileChange.
fileInfo
().
absolutePath
());
for
(MonitoredScratchPaths::const_iterator
it = s_monitoredScratchPaths.
begin
();
it != s_monitoredScratchPaths.
end
();
++it)
{
if
(changedFilePath.
isWithin
(it->
first
))
{
it->
second
(fileChange);
break
;
}
}
}
}
boost::shared_ptr<tree<FileInfo> >
monitoredPathTree
()
{
boost::shared_ptr<tree<FileInfo> >
pMonitoredTree
(
new
tree<FileInfo>());
core::system::FileScannerOptions options;
options.
recursive
=
true
;
options.
filter
= monitoredScratchFilter;
Error scanError =
scanFiles
(
FileInfo
(
monitoredParentPath
()),
options,
pMonitoredTree.
get
());
if
(scanError)
LOG_ERROR
(scanError);
return
pMonitoredTree;
}
bool
scanForMonitoredPathChanges
(boost::shared_ptr<tree<FileInfo> > pPrevTree)
{
//
check for changes
std::vector<core::system::FileChangeEvent> changes;
boost::shared_ptr<tree<FileInfo> > pCurrentTree =
monitoredPathTree
();
core::system::collectFileChangeEvents
(pPrevTree->
begin
(),
pPrevTree->
end
(),
pCurrentTree->
begin
(),
pCurrentTree->
end
(),
&changes);
//
fire events
onFilesChanged
(changes);
//
reset the tree
*pPrevTree = *pCurrentTree;
//
scan again after interval
return
true
;
}
void
onMonitoringError
(
const
Error& error)
{
//
log the error
LOG_ERROR
(error);
//
fallback to periodically scanning for changes
if
(!s_monitorByScanning)
{
s_monitorByScanning =
true
;
module_context::schedulePeriodicWork
(
boost::posix_time::seconds
(
3
),
boost::bind
(scanForMonitoredPathChanges,
monitoredPathTree
()),
true
);
}
}
void
initializeMonitoredUserScratchDir
()
{
//
setup callbacks and register
core::system::file_monitor::Callbacks cb;
cb.
onRegistrationError
= onMonitoringError;
cb.
onMonitoringError
= onMonitoringError;
cb.
onFilesChanged
= onFilesChanged;
core::system::file_monitor::registerMonitor
(
monitoredParentPath
(),
true
,
monitoredScratchFilter,
cb);
}
}
//
anonymous namespace
FilePath
registerMonitoredUserScratchDir
(
const
std::string& dirName,
const
OnFileChange& onFileChange)
{
//
create the subdir
FilePath dirPath =
monitoredParentPath
().
completePath
(dirName);
Error error = dirPath.
ensureDirectory
();
if
(error)
LOG_ERROR
(error);
//
register the path
s_monitoredScratchPaths[dirPath] = onFileChange;
//
return it
return
dirPath;
}
namespace
{
//
manage signals used for custom save and restore
class
SuspendHandlers
: boost::noncopyable
{
public:
SuspendHandlers
() : nextGroup_(
0
) {}
public:
void
add
(
const
SuspendHandler& handler)
{
int
group = nextGroup_++;
suspendSignal_.
connect
(group, handler.
suspend
());
resumeSignal_.
connect
(group, handler.
resume
());
}
void
suspend
(
const
r::session::RSuspendOptions& options,
Settings* pSettings)
{
suspendSignal_
(options, pSettings);
}
void
resume
(
const
Settings& settings)
{
resumeSignal_
(settings);
}
private:
//
use groups to ensure signal order. call suspend handlers in order
//
of subscription and call resume handlers in reverse order of
//
subscription.
int
nextGroup_;
RSTUDIO_BOOST_SIGNAL
<
void
(
const
r::session::RSuspendOptions&,Settings*),
RSTUDIO_BOOST_LAST_VALUE
<
void
>,
int
,
std::less<
int
> > suspendSignal_;
RSTUDIO_BOOST_SIGNAL
<
void
(
const
Settings&),
RSTUDIO_BOOST_LAST_VALUE
<
void
>,
int
,
std::greater<
int
> > resumeSignal_;
};
//
handlers instance
SuspendHandlers&
suspendHandlers
()
{
static
SuspendHandlers instance;
return
instance;
}
}
//
anonymous namespace
void
addSuspendHandler
(
const
SuspendHandler& handler)
{
suspendHandlers
().
add
(handler);
}
void
onSuspended
(
const
r::session::RSuspendOptions& options,
Settings* pPersistentState)
{
pPersistentState->
beginUpdate
();
suspendHandlers
().
suspend
(options, pPersistentState);
pPersistentState->
endUpdate
();
}
void
onResumed
(
const
Settings& persistentState)
{
suspendHandlers
().
resume
(persistentState);
}
//
idle work
namespace
{
typedef
std::vector<boost::shared_ptr<ScheduledCommand> >
ScheduledCommands;
ScheduledCommands s_scheduledCommands;
ScheduledCommands s_idleScheduledCommands;
void
addScheduledCommand
(boost::shared_ptr<ScheduledCommand> pCommand,
bool
idleOnly)
{
if
(idleOnly)
s_idleScheduledCommands.
push_back
(pCommand);
else
s_scheduledCommands.
push_back
(pCommand);
}
void
executeScheduledCommands
(ScheduledCommands* pCommands)
{
//
make a copy of scheduled commands before executing them
//
(this is because a scheduled command could result in
//
R code executing which in turn could cause the list of
//
scheduled commands to be mutated and these iterators
//
invalidated)
ScheduledCommands commands = *pCommands;
//
execute all commands
std::for_each
(commands.
begin
(),
commands.
end
(),
boost::bind
(&ScheduledCommand::execute, _1));
//
remove any commands which are finished
pCommands->
erase
(
std::remove_if
(
pCommands->
begin
(),
pCommands->
end
(),
boost::bind
(&ScheduledCommand::finished, _1)),
pCommands->
end
());
}
}
//
anonymous namespace
void
scheduleIncrementalWork
(
const
boost::posix_time::time_duration& incrementalDuration,
const
boost::function<
bool
()>& execute,
bool idleOnly)
{
addScheduledCommand
(boost::shared_ptr<ScheduledCommand>(
new
IncrementalCommand
(incrementalDuration,
execute)),
idleOnly);
}
void
scheduleIncrementalWork
(
const
boost::posix_time::time_duration& initialDuration,
const
boost::posix_time::time_duration& incrementalDuration,
const
boost::function<
bool
()>& execute,
bool idleOnly)
{
addScheduledCommand
(boost::shared_ptr<ScheduledCommand>(
new
IncrementalCommand
(initialDuration,
incrementalDuration,
execute)),
idleOnly);
}
void
schedulePeriodicWork
(
const
boost::posix_time::time_duration& period,
const
boost::function<
bool
()> &execute,
bool idleOnly,
bool immediate)
{
addScheduledCommand
(boost::shared_ptr<ScheduledCommand>(
new
PeriodicCommand
(period, execute, immediate)),
idleOnly);
}
namespace
{
bool
performDelayedWork
(
const
boost::function<
void
()> &execute,
boost::shared_ptr<bool> pExecuted)
{
if
(*pExecuted)
return
false
;
*pExecuted =
true
;
execute
();
return
false
;
}
bool
isPackagePosixMakefile
(
const
FilePath& srcPath)
{
if
(!srcPath.
exists
())
return
false
;
using
namespace
projects
;
ProjectContext& context =
session::projects::projectContext
();
if
(!context.
hasProject
())
return
false
;
if
(context.
config
().
buildType
!= r_util::
kBuildTypePackage
)
return
false
;
FilePath parentDir = srcPath.
getParent
();
if
(parentDir.
getFilename
() !=
"
src
"
)
return
false
;
FilePath packagePath = context.
buildTargetPath
();
if
(parentDir.
getParent
() != packagePath)
return
false
;
std::string filename = srcPath.
getFilename
();
return
(filename ==
"
Makevars
"
||
filename ==
"
Makevars.in
"
||
filename ==
"
Makefile
"
||
filename ==
"
Makefile.in
"
);
}
void
performIdleOnlyAsyncRpcMethod
(
const
core::json::JsonRpcRequest& request,
const
core::json::JsonRpcFunctionContinuation& continuation,
const
core::json::JsonRpcAsyncFunction& function)
{
if
(request.
isBackgroundConnection
)
{
module_context::scheduleDelayedWork
(
boost::posix_time::milliseconds
(
100
),
boost::bind
(function, request, continuation),
true
);
}
else
{
function
(request, continuation);
}
}
}
//
anonymous namespeace
void
scheduleDelayedWork
(
const
boost::posix_time::time_duration& period,
const
boost::function<
void
()> &execute,
bool idleOnly)
{
boost::shared_ptr<
bool
>
pExecuted
(
new
bool
(
false
));
schedulePeriodicWork
(period,
boost::bind
(performDelayedWork, execute, pExecuted),
idleOnly,
false
);
}
void
onBackgroundProcessing
(
bool
isIdle)
{
//
allow process supervisor to poll for events
processSupervisor
().
poll
();
//
check for file monitor changes
core::system::file_monitor::checkForChanges
();
//
fire event
events
().
onBackgroundProcessing
(isIdle);
//
execute incremental commands
executeScheduledCommands
(&s_scheduledCommands);
if
(isIdle)
executeScheduledCommands
(&s_idleScheduledCommands);
}
#
ifdef
_WIN32
namespace
{
BOOL
CALLBACK
consoleCtrlHandler
(
DWORD
type)
{
switch
(type)
{
case
CTRL_C_EVENT
:
case
CTRL_BREAK_EVENT
:
rstudio::r::exec::setInterruptsPending
(
true
);
return
true
;
default
:
return
false
;
}
}
}
//
end anonymous namespace
#
endif
void
initializeConsoleCtrlHandler
()
{
#
ifdef
_WIN32
//
accept Ctrl + C interrupts
::SetConsoleCtrlHandler
(
nullptr
,
FALSE
);
//
remove an old registration (if any)
::SetConsoleCtrlHandler
(consoleCtrlHandler,
FALSE
);
//
register console control handler
::SetConsoleCtrlHandler
(consoleCtrlHandler,
TRUE
);
#
endif
}
Error
registerIdleOnlyAsyncRpcMethod
(
const
std::string& name,
const
core::json::JsonRpcAsyncFunction& function)
{
return
registerAsyncRpcMethod
(name,
boost::bind
(performIdleOnlyAsyncRpcMethod,
_1, _2, function));
}
core::string_utils::LineEnding
lineEndings
(
const
core::FilePath& srcFile)
{
//
potential special case for Makevars
if
(
prefs::userPrefs
().
useNewlinesInMakefiles
() &&
isPackagePosixMakefile
(srcFile))
return
string_utils::LineEndingPosix;
//
get the global default behavior
string_utils::LineEnding lineEndings =
prefs::userPrefs
().
lineEndings
();
//
use project-level override if available
using
namespace
session
::projects
;
ProjectContext& context =
projectContext
();
if
(context.
hasProject
())
{
if
(context.
config
().
lineEndings
!= r_util::
kLineEndingsUseDefault
)
lineEndings = (string_utils::LineEnding)context.
config
().
lineEndings
;
}
//
if we are doing no conversion (passthrough) and there is an existing file
//
then we need to peek inside it to see what the existing line endings are
if
(lineEndings == string_utils::LineEndingPassthrough)
string_utils::detectLineEndings
(srcFile, &lineEndings);
//
return computed lineEndings
return
lineEndings;
}
Error
readAndDecodeFile
(
const
FilePath& filePath,
const
std::string& encoding,
bool
allowSubstChars,
std::string* pContents)
{
//
read contents
std::string encodedContents;
Error error =
readStringFromFile
(filePath, &encodedContents,
options
().
sourceLineEnding
());
if
(error)
return
error ;
//
convert to UTF-8
return
convertToUtf8
(encodedContents,
encoding,
allowSubstChars,
pContents);
}
Error
convertToUtf8
(
const
std::string& encodedContents,
const
std::string& encoding,
bool
allowSubstChars,
std::string* pContents)
{
Error error;
error =
r::util::iconvstr
(encodedContents, encoding,
"
UTF-8
"
,
allowSubstChars, pContents);
if
(error)
return
error;
stripBOM
(pContents);
//
Detect invalid UTF-8 sequences and recover
error =
string_utils::utf8Clean
(pContents->
begin
(),
pContents->
end
(),
'
?
'
);
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL