-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
SessionMain.cpp
2156 lines (1850 loc) · 67.1 KB
/
SessionMain.cpp
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
/*
* SessionMain.cpp
*
* Copyright (C) 2009-19 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 <session/SessionMain.hpp>
// required to avoid Win64 winsock order of include
// compilation problem
#include <boost/asio/io_service.hpp>
#ifndef _WIN32
#include <sys/types.h>
#include <unistd.h>
#endif
#include <string>
#include <vector>
#include <queue>
#include <map>
#include <algorithm>
#include <cstdlib>
#include <csignal>
#include <limits>
#include <boost/shared_ptr.hpp>
#include <boost/function.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/format.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/join.hpp>
#include <core/CrashHandler.hpp>
#include <core/BoostSignals.hpp>
#include <core/BoostThread.hpp>
#include <core/ConfigUtils.hpp>
#include <core/FileLock.hpp>
#include <core/Exec.hpp>
#include <core/Scope.hpp>
#include <core/Settings.hpp>
#include <core/Thread.hpp>
#include <core/Log.hpp>
#include <core/system/System.hpp>
#include <core/ProgramStatus.hpp>
#include <core/FileSerializer.hpp>
#include <core/http/URL.hpp>
#include <core/http/Request.hpp>
#include <core/http/Response.hpp>
#include <core/http/UriHandler.hpp>
#include <core/json/JsonRpc.hpp>
#include <core/system/Crypto.hpp>
#include <core/system/Process.hpp>
#include <core/system/Environment.hpp>
#include <core/system/ParentProcessMonitor.hpp>
#include <core/system/FileMonitor.hpp>
#include <core/text/TemplateFilter.hpp>
#include <core/r_util/RSessionContext.hpp>
#include <core/r_util/REnvironment.hpp>
#include <core/WaitUtils.hpp>
#include <r/RJsonRpc.hpp>
#include <r/RExec.hpp>
#include <r/ROptions.hpp>
#include <r/RFunctionHook.hpp>
#include <r/RInterface.hpp>
#include <r/session/RSession.hpp>
#include <r/session/RSessionState.hpp>
#include <r/session/RClientState.hpp>
#include <r/session/RConsoleActions.hpp>
#include <r/session/RConsoleHistory.hpp>
#include <r/session/RGraphics.hpp>
#include <r/session/REventLoop.hpp>
#include <r/RUtil.hpp>
#include <monitor/MonitorClient.hpp>
#include <session/SessionConstants.hpp>
#include <session/SessionOptions.hpp>
#include <session/SessionSourceDatabase.hpp>
#include <session/SessionPersistentState.hpp>
#include <session/SessionContentUrls.hpp>
#include <session/SessionScopes.hpp>
#include <session/SessionClientEventService.hpp>
#include <session/SessionUrlPorts.hpp>
#include <session/RVersionSettings.hpp>
#include <shared_core/Error.hpp>
#include <shared_core/FilePath.hpp>
#include <shared_core/StderrLogDestination.hpp>
#include "SessionAddins.hpp"
#include "SessionModuleContextInternal.hpp"
#include "SessionClientEventQueue.hpp"
#include "SessionClientInit.hpp"
#include "SessionConsoleInput.hpp"
#include "SessionDirs.hpp"
#include "SessionHttpMethods.hpp"
#include "SessionInit.hpp"
#include "SessionMainProcess.hpp"
#include "SessionRpc.hpp"
#include "SessionSuspend.hpp"
#include <session/SessionRUtil.hpp>
#include <session/SessionPackageProvidedExtension.hpp>
#include "modules/RStudioAPI.hpp"
#include "modules/SessionAbout.hpp"
#include "modules/SessionAgreement.hpp"
#include "modules/SessionAskPass.hpp"
#include "modules/SessionAskSecret.hpp"
#include "modules/SessionAuthoring.hpp"
#include "modules/SessionBreakpoints.hpp"
#include "modules/SessionHTMLPreview.hpp"
#include "modules/SessionCodeSearch.hpp"
#include "modules/SessionConfigFile.hpp"
#include "modules/SessionConsole.hpp"
#include "modules/SessionCRANMirrors.hpp"
#include "modules/SessionCrypto.hpp"
#include "modules/SessionErrors.hpp"
#include "modules/SessionFiles.hpp"
#include "modules/SessionFind.hpp"
#include "modules/SessionDependencies.hpp"
#include "modules/SessionDependencyList.hpp"
#include "modules/SessionDirty.hpp"
#include "modules/SessionWorkbench.hpp"
#include "modules/SessionHelp.hpp"
#include "modules/SessionPlots.hpp"
#include "modules/SessionPath.hpp"
#include "modules/SessionPackages.hpp"
#include "modules/SessionPackrat.hpp"
#include "modules/SessionPlumberViewer.hpp"
#include "modules/SessionProfiler.hpp"
#include "modules/SessionRAddins.hpp"
#include "modules/SessionRCompletions.hpp"
#include "modules/SessionRenv.hpp"
#include "modules/SessionRPubs.hpp"
#include "modules/SessionRHooks.hpp"
#include "modules/SessionRSConnect.hpp"
#include "modules/SessionShinyViewer.hpp"
#include "modules/SessionSpelling.hpp"
#include "modules/SessionSource.hpp"
#include "modules/SessionTests.hpp"
#include "modules/SessionThemes.hpp"
#include "modules/SessionTutorial.hpp"
#include "modules/SessionUpdates.hpp"
#include "modules/SessionVCS.hpp"
#include "modules/SessionHistory.hpp"
#include "modules/SessionLimits.hpp"
#include "modules/SessionLists.hpp"
#include "modules/SessionUserPrefs.hpp"
#include "modules/build/SessionBuild.hpp"
#include "modules/clang/SessionClang.hpp"
#include "modules/connections/SessionConnections.hpp"
#include "modules/customsource/SessionCustomSource.hpp"
#include "modules/data/SessionData.hpp"
#include "modules/environment/SessionEnvironment.hpp"
#include "modules/jobs/SessionJobs.hpp"
#include "modules/overlay/SessionOverlay.hpp"
#include "modules/plumber/SessionPlumber.hpp"
#include "modules/presentation/SessionPresentation.hpp"
#include "modules/preview/SessionPreview.hpp"
#include "modules/rmarkdown/RMarkdownTemplates.hpp"
#include "modules/rmarkdown/SessionRMarkdown.hpp"
#include "modules/rmarkdown/SessionRmdNotebook.hpp"
#include "modules/shiny/SessionShiny.hpp"
#include "modules/sql/SessionSql.hpp"
#include "modules/stan/SessionStan.hpp"
#include "modules/viewer/SessionViewer.hpp"
#include "modules/SessionDiagnostics.hpp"
#include "modules/SessionMarkers.hpp"
#include "modules/SessionSnippets.hpp"
#include "modules/SessionUserCommands.hpp"
#include "modules/SessionRAddins.hpp"
#include "modules/mathjax/SessionMathJax.hpp"
#include "modules/SessionLibPathsIndexer.hpp"
#include "modules/SessionObjectExplorer.hpp"
#include "modules/SessionReticulate.hpp"
#include "modules/SessionCrashHandler.hpp"
#include "modules/SessionRVersions.hpp"
#include "modules/SessionTerminal.hpp"
#include <session/SessionProjectTemplate.hpp>
#include "modules/SessionGit.hpp"
#include "modules/SessionSVN.hpp"
#include <session/SessionConsoleProcess.hpp>
#include <session/projects/ProjectsSettings.hpp>
#include <session/projects/SessionProjects.hpp>
#include "projects/SessionProjectsInternal.hpp"
#include <session/prefs/UserPrefs.hpp>
#include <session/prefs/UserState.hpp>
#include "workers/SessionWebRequestWorker.hpp"
#include <session/SessionHttpConnectionListener.hpp>
#include "session-config.h"
#include <tests/TestRunner.hpp>
using namespace rstudio;
using namespace rstudio::core;
// Use rsession alias to avoid collision with 'session'
// object brought in by Catch
namespace rsession = rstudio::session;
using namespace rsession;
using namespace rsession::client_events;
// forward-declare overlay methods
namespace rstudio {
namespace session {
bool disableExecuteRprofile()
{
// check for session-specific override
if (options().rRunRprofile() == kRunRprofileNo)
return true;
if (options().rRunRprofile() == kRunRprofileYes)
return false;
bool disableExecuteRprofile = false;
const projects::ProjectContext& projContext = projects::projectContext();
if (projContext.hasProject())
{
disableExecuteRprofile = projContext.config().disableExecuteRprofile;
}
return disableExecuteRprofile;
}
bool quitChildProcesses()
{
// allow project override
const projects::ProjectContext& projContext = projects::projectContext();
if (projContext.hasProject())
{
switch(projContext.config().quitChildProcessesOnExit)
{
case r_util::YesValue:
return true;
case r_util::NoValue:
return false;
default:
// fall through
break;
}
}
// no project override
return rsession::options().quitChildProcessesOnExit();
}
// terminates all child processes, including those unknown to us
// no waiting is done to ensure the children shutdown
// this is merely a best effort to stop children
void terminateAllChildProcesses()
{
if (!quitChildProcesses())
return;
Error error = system::terminateChildProcesses();
if (error)
LOG_ERROR(error);
}
namespace overlay {
Error initialize();
} // namespace overlay
} // namespace session
} // namespace rstudio
namespace {
// R browseUrl handlers
std::vector<module_context::RBrowseUrlHandler> s_rBrowseUrlHandlers;
// R browseFile handlers
std::vector<module_context::RBrowseFileHandler> s_rBrowseFileHandlers;
// indicates whether we should destroy the session at cleanup time
// (true if the user does a full quit)
bool s_destroySession = false;
// did we fail to coerce the charset to UTF-8
bool s_printCharsetWarning = false;
#ifdef _WIN32
BOOL CALLBACK handleConsoleCtrl(DWORD type)
{
switch (type)
{
case CTRL_C_EVENT:
case CTRL_BREAK_EVENT:
rstudio::r::exec::setInterruptsPending(true);
return true;
default:
return false;
}
}
#endif
void handleINT(int)
{
rstudio::r::exec::setInterruptsPending(true);
}
void detectChanges(module_context::ChangeSource source)
{
module_context::events().onDetectChanges(source);
}
// allow console_input requests to come in when we aren't explicitly waiting
// on them (i.e. waitForMethod("console_input")). place them into into a buffer
// which is then checked by rConsoleRead prior to it calling waitForMethod
Error bufferConsoleInput(const core::json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
// extract the input
return console_input::extractConsoleInput(request);
}
void doSuspendForRestart(const rstudio::r::session::RSuspendOptions& options)
{
module_context::consoleWriteOutput("\nRestarting R session...\n\n");
rstudio::r::session::suspendForRestart(options);
}
Error suspendForRestart(const core::json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
rstudio::r::session::RSuspendOptions options(EX_CONTINUE);
Error error = json::readObjectParam(
request.params, 0,
"save_minimal", &(options.saveMinimal),
"save_workspace", &(options.saveWorkspace),
"exclude_packages", &(options.excludePackages));
if (error)
return error;
pResponse->setAfterResponse(boost::bind(doSuspendForRestart, options));
return Success();
}
Error ping(const core::json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
return Success();
}
Error startClientEventService()
{
return clientEventService().start(rsession::persistentState().activeClientId());
}
Error registerSignalHandlers()
{
using boost::bind;
using namespace rstudio::core::system;
ExecBlock registerBlock;
#ifdef _WIN32
// accept Ctrl + C interrupts
::SetConsoleCtrlHandler(nullptr, FALSE);
// register console control handler
::SetConsoleCtrlHandler(handleConsoleCtrl, TRUE);
#endif
// SIGINT: set interrupt flag on R session
registerBlock.addFunctions()
(bind(handleSignal, SigInt, handleINT));
// USR1 and USR2: perform suspend in server mode
if (rsession::options().programMode() == kSessionProgramModeServer)
{
registerBlock.addFunctions()
(bind(handleSignal, SigUsr1, suspend::handleUSR1))
(bind(handleSignal, SigUsr2, suspend::handleUSR2));
}
// USR1 and USR2: ignore in desktop mode
else
{
registerBlock.addFunctions()
(bind(ignoreSignal, SigUsr1))
(bind(ignoreSignal, SigUsr2));
}
return registerBlock.execute();
}
Error runPreflightScript()
{
// alias options
Options& options = rsession::options();
// run the preflight script (if specified)
if (rsession::options().programMode() == kSessionProgramModeServer)
{
FilePath preflightScriptPath = options.preflightScriptPath();
if (!preflightScriptPath.isEmpty())
{
if (preflightScriptPath.exists())
{
// run the script (ignore errors and continue no matter what
// the outcome of the script is)
std::string script = preflightScriptPath.getAbsolutePath();
core::system::ProcessResult result;
Error error = runCommand(script,
core::system::ProcessOptions(),
&result);
if (error)
{
error.addProperty("preflight-script", script);
LOG_ERROR(error);
}
}
else
{
LOG_WARNING_MESSAGE("preflight script does not exist: " +
preflightScriptPath.getAbsolutePath());
}
}
}
// always return success
return Success();
}
void exitEarly(int status)
{
FileLock::cleanUp();
::exit(status);
}
Error rInit(const rstudio::r::session::RInitInfo& rInitInfo)
{
// save state we need to reference later
suspend::setSessionResumed(rInitInfo.resumed);
// record built-in waitForMethod handlers
module_context::registerWaitForMethod(kLocatorCompleted);
module_context::registerWaitForMethod(kEditCompleted);
module_context::registerWaitForMethod(kChooseFileCompleted);
module_context::registerWaitForMethod(kUserPromptCompleted);
module_context::registerWaitForMethod(kHandleUnsavedChangesCompleted);
module_context::registerWaitForMethod(kRStudioAPIShowDialogMethod);
// execute core initialization functions
using boost::bind;
using namespace rstudio::core::system;
using namespace rsession::module_context;
ExecBlock initialize ;
initialize.addFunctions()
// client event service
(startClientEventService)
// rpc methods
(rpc::initialize)
// json-rpc listeners
(bind(registerRpcMethod, kConsoleInput, bufferConsoleInput))
(bind(registerRpcMethod, "suspend_for_restart", suspendForRestart))
(bind(registerRpcMethod, "ping", ping))
// signal handlers
(registerSignalHandlers)
// main module context
(module_context::initialize)
// projects (early project init required -- module inits below
// can then depend on e.g. computed defaultEncoding)
(projects::initialize)
// source database
(source_database::initialize)
// content urls
(content_urls::initialize)
// URL port transformations
(url_ports::initialize)
// overlay R
(bind(sourceModuleRFile, "SessionOverlay.R"))
// addins
(addins::initialize)
// console processes
(console_process::initialize)
// r utils
(r_utils::initialize)
// modules with c++ implementations
(modules::prefs::initialize)
(modules::spelling::initialize)
(modules::lists::initialize)
(modules::path::initialize)
(modules::limits::initialize)
(modules::ppe::initialize)
(modules::ask_pass::initialize)
(modules::agreement::initialize)
(modules::console::initialize)
#ifdef RSTUDIO_SERVER
(modules::crypto::initialize)
#endif
(modules::code_search::initialize)
(modules::clang::initialize)
(modules::connections::initialize)
(modules::files::initialize)
(modules::find::initialize)
(modules::environment::initialize)
(modules::dependencies::initialize)
(modules::dependency_list::initialize)
(modules::dirty::initialize)
(modules::workbench::initialize)
(modules::data::initialize)
(modules::help::initialize)
(modules::presentation::initialize)
(modules::preview::initialize)
(modules::plots::initialize)
(modules::packages::initialize)
(modules::cran_mirrors::initialize)
(modules::profiler::initialize)
(modules::viewer::initialize)
(modules::rmarkdown::initialize)
(modules::rmarkdown::notebook::initialize)
(modules::rmarkdown::templates::initialize)
(modules::rpubs::initialize)
(modules::shiny::initialize)
(modules::sql::initialize)
(modules::stan::initialize)
(modules::plumber::initialize)
(modules::source::initialize)
(modules::source_control::initialize)
(modules::authoring::initialize)
(modules::html_preview::initialize)
(modules::history::initialize)
(modules::build::initialize)
(modules::overlay::initialize)
(modules::breakpoints::initialize)
(modules::errors::initialize)
(modules::updates::initialize)
(modules::about::initialize)
(modules::shiny_viewer::initialize)
(modules::plumber_viewer::initialize)
(modules::rsconnect::initialize)
(modules::packrat::initialize)
(modules::renv::initialize)
(modules::rhooks::initialize)
(modules::r_packages::initialize)
(modules::diagnostics::initialize)
(modules::markers::initialize)
(modules::snippets::initialize)
(modules::user_commands::initialize)
(modules::r_addins::initialize)
(modules::projects::templates::initialize)
(modules::mathjax::initialize)
(modules::rstudioapi::initialize)
(modules::libpaths::initialize)
(modules::explorer::initialize)
(modules::ask_secret::initialize)
(modules::reticulate::initialize)
(modules::tests::initialize)
(modules::jobs::initialize)
(modules::themes::initialize)
(modules::customsource::initialize)
(modules::crash_handler::initialize)
(modules::r_versions::initialize)
(modules::terminal::initialize)
(modules::config_file::initialize)
(modules::tutorial::initialize)
// workers
(workers::web_request::initialize)
// R code
(bind(sourceModuleRFile, "SessionCodeTools.R"))
(bind(sourceModuleRFile, "SessionCompletionHooks.R"))
(bind(sourceModuleRFile, "SessionPatches.R"))
// unsupported functions
(bind(rstudio::r::function_hook::registerUnsupported, "bug.report", "utils"))
(bind(rstudio::r::function_hook::registerUnsupported, "help.request", "utils"))
;
Error error = initialize.execute();
if (error)
return error;
// if we are in verify installation mode then we should exit (successfully) now
if (rsession::options().verifyInstallation())
{
// in desktop mode we write a success message and execute diagnostics
if (rsession::options().programMode() == kSessionProgramModeDesktop)
{
std::cout << "Successfully initialized R session."
<< std::endl << std::endl;
FilePath diagFile = module_context::sourceDiagnostics();
if (!diagFile.isEmpty())
{
std::cout << "Diagnostics report written to: "
<< diagFile << std::endl
<< "Please audit the report and remove any sensitive information "
<< "before submitting." << std::endl << std::endl;
Error error = rstudio::r::exec::RFunction(".rs.showDiagnostics").call();
if (error)
LOG_ERROR(error);
}
}
rsession::options().verifyInstallationHomeDir().removeIfExists();
int exitCode = modules::overlay::verifyInstallation();
exitEarly(exitCode);
}
// run unit tests
if (rsession::options().runTests())
{
int result = tests::run();
exitEarly(result);
}
// register all of the json rpc methods implemented in R
json::JsonRpcMethods rMethods ;
error = rstudio::r::json::getRpcMethods(&rMethods);
if (error)
return error ;
for (const json::JsonRpcMethod& method : rMethods)
{
registerRpcMethod(json::adaptMethodToAsync(method));
}
// add gwt handlers if we are running desktop mode
if ((rsession::options().programMode() == kSessionProgramModeDesktop) ||
rsession::options().standalone())
{
http_methods::registerGwtHandlers();
}
// enque abend warning event if necessary (but not in standalone
// mode since those processes are often aborted unceremoniously)
using namespace rsession::client_events;
if (rsession::persistentState().hadAbend() && !options().standalone())
{
LOG_ERROR_MESSAGE("session hadabend");
ClientEvent abendWarningEvent(kAbendWarning);
rsession::clientEventQueue().add(abendWarningEvent);
}
if (s_printCharsetWarning)
rstudio::r::exec::warning("Character set is not UTF-8; please change your locale");
// propagate console history options
rstudio::r::session::consoleHistory().setRemoveDuplicates(
prefs::userPrefs().removeHistoryDuplicates());
// register function editor on windows
#ifdef _WIN32
error = rstudio::r::exec::RFunction(".rs.registerFunctionEditor").call();
if (error)
LOG_ERROR(error);
#endif
// clear out stale uploaded tmp files
if (module_context::userUploadedFilesScratchPath().exists())
{
std::vector<FilePath> childPaths;
error = module_context::userUploadedFilesScratchPath().getChildren(childPaths);
if (error)
LOG_ERROR(error);
constexpr double secondsPerDay = 60*60*24;
for (const FilePath& childPath : childPaths)
{
double diffTime = std::difftime(std::time(nullptr),
childPath.getLastWriteTime());
if (diffTime > secondsPerDay)
{
Error error = childPath.remove();
if (error)
LOG_ERROR(error);
}
}
}
// set flag indicating we had an abnormal end (if this doesn't get
// unset by the time we launch again then we didn't terminate normally
// i.e. either the process dying unexpectedly or a call to R_Suicide)
rsession::persistentState().setAbend(true);
// begin session
using namespace module_context;
activeSession().beginSession(rVersion(), rHomeDir(), rVersionLabel());
// setup fork handlers
main_process::setupForkHandlers();
// success!
return Success();
}
void notifyIfRVersionChanged()
{
using namespace rstudio::r::session::state;
SessionStateInfo info = getSessionStateInfo();
if (info.activeRVersion != info.suspendedRVersion)
{
const char* fmt =
"R version change [%1% -> %2%] detected when restoring session; "
"search path not restored\n";
boost::format formatter(fmt);
formatter
% std::string(info.suspendedRVersion)
% std::string(info.activeRVersion);
std::string msg = formatter.str();
::REprintf(msg.c_str());
}
}
void rSessionInitHook(bool newSession)
{
// allow any packages listening to complete initialization
modules::rhooks::invokeHook(kSessionInitHook, newSession);
// finish off initialization
module_context::events().afterSessionInitHook(newSession);
// notify the user if the R version has changed
notifyIfRVersionChanged();
// fire an event to the client
ClientEvent event(client_events::kDeferredInitCompleted);
module_context::enqueClientEvent(event);
}
void rDeferredInit(bool newSession)
{
module_context::events().onDeferredInit(newSession);
// schedule execution of the session init hook
module_context::scheduleDelayedWork(
boost::posix_time::seconds(1),
boost::bind(rSessionInitHook, newSession));
}
int rEditFile(const std::string& file)
{
// read file contents
FilePath filePath(file);
std::string fileContents;
if (filePath.exists())
{
Error readError = core::readStringFromFile(filePath, &fileContents);
if (readError)
{
LOG_ERROR(readError);
return 1; // r will raise/report an error indicating edit failed
}
}
// fire edit event
ClientEvent editEvent = rsession::showEditorEvent(fileContents, true, false);
rsession::clientEventQueue().add(editEvent);
// wait for edit_completed
json::JsonRpcRequest request ;
bool succeeded = http_methods::waitForMethod(kEditCompleted,
editEvent,
suspend::disallowSuspend,
&request);
if (!succeeded)
return false;
// user cancelled edit
if (request.params[0].isNull())
{
return 0; // no-op, object will be re-parsed from original content
}
// user confirmed edit
else
{
// extract the content
std::string editedFileContents;
Error error = json::readParam(request.params, 0, &editedFileContents);
if (error)
{
LOG_ERROR(error);
return 1; // error (r will notify user via the console)
}
// write the content back to the file (append newline expected by R)
editedFileContents += "\n";
Error writeError = core::writeStringToFile(filePath, editedFileContents);
if (writeError)
{
LOG_ERROR(writeError);
return 1 ; // error (r will notify user via the console)
}
// success!
return 0 ;
}
}
FilePath rChooseFile(bool newFile)
{
// fire choose file event
ClientEvent chooseFileEvent(kChooseFile, newFile);
rsession::clientEventQueue().add(chooseFileEvent);
// wait for choose_file_completed
json::JsonRpcRequest request ;
bool succeeded = http_methods::waitForMethod(kChooseFileCompleted,
chooseFileEvent,
suspend::disallowSuspend,
&request);
if (!succeeded)
return FilePath();
// extract the file name
std::string fileName;
if (!request.params[0].isNull())
{
Error error = json::readParam(request.params, 0, &fileName);
if (error)
LOG_ERROR(error);
// resolve aliases and return it
return module_context::resolveAliasedPath(fileName);
}
else
{
return FilePath();
}
}
void rBusy(bool busy)
{
if (main_process::wasForked())
return;
// screen out busy = true events that occur when R isn't busy
if (busy && !console_input::executing())
return;
ClientEvent busyEvent(kBusy, busy);
rsession::clientEventQueue().add(busyEvent);
}
void rConsoleWrite(const std::string& output, int otype)
{
if (main_process::wasForked())
return;
int event = otype == 1 ? kConsoleWriteError : kConsoleWriteOutput;
ClientEvent writeEvent(event, output);
rsession::clientEventQueue().add(writeEvent);
// fire event
module_context::events().onConsoleOutput(
otype == 1 ? module_context::ConsoleOutputError :
module_context::ConsoleOutputNormal,
output);
}
void rConsoleHistoryReset()
{
json::Array historyJson;
rstudio::r::session::consoleHistory().asJson(&historyJson);
json::Object resetJson;
resetJson["history"] = historyJson;
resetJson["preserve_ui_context"] = false;
ClientEvent event(kConsoleResetHistory, resetJson);
rsession::clientEventQueue().add(event);
}
bool rLocator(double* x, double* y)
{
// since locator can be called in a loop we need to checkForChanges
// here (because we'll never get back to the REPL). this enables
// identify() to correctly update the plot after each click
detectChanges(module_context::ChangeSourceREPL);
// fire locator event
ClientEvent locatorEvent(kLocator);
rsession::clientEventQueue().add(locatorEvent);
// wait for locator_completed
json::JsonRpcRequest request ;
bool succeeded = http_methods::waitForMethod(kLocatorCompleted,
locatorEvent,
suspend::disallowSuspend,
&request);
if (!succeeded)
return false;
// see if we got a point
if ((request.params.getSize() > 0) && !request.params[0].isNull())
{
// read the x and y
Error error = json::readObjectParam(request.params, 0,
"x", x,
"y", y);
if (error)
{
LOG_ERROR(error);
return false;
}
// return true
return true;
}
else
{
return false;
}
}
void rShowFile(const std::string& title, const FilePath& filePath, bool del)
{
if (rsession::options().programMode() == kSessionProgramModeServer)
{
// for files in the temporary directory, show as content
//
// (perform this check first to handle case where
// tempdir lives within the user's home directory)
if (filePath.isWithin(module_context::tempDir()))
{
module_context::showContent(title, filePath);
}
// for files in the user's home directory and pdfs use an external browser
else if (module_context::isVisibleUserFile(filePath) ||
(filePath.getExtensionLowerCase() == ".pdf"))
{
module_context::showFile(filePath);
}
// otherwise, show as content
else
{
module_context::showContent(title, filePath);
}
}
else // (rsession::options().programMode() == kSessionProgramModeDesktop
{
#ifdef _WIN32
if (!filePath.getExtension().empty())
{
module_context::showFile(filePath);
del = false;
}
else
{
module_context::showContent(title, filePath);
}