/
SessionWorkspace.cpp
343 lines (293 loc) · 9.93 KB
/
SessionWorkspace.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
/*
* SessionWorkspace.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* 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 "SessionWorkspace.hpp"
#include <algorithm>
#include <boost/bind.hpp>
#include <boost/format.hpp>
#include <boost/utility.hpp>
#include <core/Error.hpp>
#include <core/Log.hpp>
#include <core/Exec.hpp>
#include <core/FilePath.hpp>
#include <core/json/JsonRpc.hpp>
#include <r/RExec.hpp>
#include <r/RRoutines.hpp>
#include <r/RErrorCategory.hpp>
#include <r/session/RSession.hpp>
#include <session/SessionModuleContext.hpp>
#include <session/SessionUserSettings.hpp>
using namespace core ;
using namespace r::sexp;
using namespace r::exec;
namespace session {
namespace modules {
namespace workspace {
namespace {
bool handleRBrowseEnv(const core::FilePath& filePath)
{
if (filePath.filename() == "wsbrowser.html")
{
module_context::showContent("R objects", filePath);
return true;
}
else
{
return false;
}
}
json::Value classOfGlobalVar(SEXP globalVar)
{
std::string value;
Error error = r::exec::RFunction(".rs.getSingleClass",
globalVar).call(&value);
if (error)
{
LOG_ERROR(error);
return json::Value(); // return null
}
else
{
return value;
}
}
json::Value valueOfGlobalVar(SEXP globalVar)
{
std::string value;
Error error = r::exec::RFunction(".rs.valueAsString",
globalVar).call(&value);
if (error)
{
LOG_ERROR(error);
return json::Value(); // return null
}
else
{
return value;
}
}
json::Value descriptionOfGlobalVar(SEXP globalVar)
{
std::string value;
Error error = r::exec::RFunction(".rs.valueDescription",
globalVar).call(&value);
if (error)
{
LOG_ERROR(error);
return json::Value(); // return null
}
else
{
return value;
}
}
json::Value jsonValueForGlobalVar(const std::string& name)
{
json::Object jsonObject ;
jsonObject["name"] = name;
// get R alias to object and get its type and lengt
//
// NOTE: check for isLanguage is a temporary fix for error messages
// that were printed at the console for a <- bquote(test()) -- this
// was the result of errors being thrown from the .rs.valueDescription, etc.
// calls above used to probe for object info. interestingly when these
// same calls are made from .rs.rpc.list_objects no errors are thrown.
// the practical impact of this workaround is that immediately after
// assignment language expressions show up as "(unknown)" but then are
// correctly displayed in refreshed listings of the workspace.
//
SEXP globalVar = findVar(name);
if ((globalVar != R_UnboundValue) && !r::sexp::isLanguage(globalVar))
{
Protect rProtect(globalVar);
jsonObject["type"] = classOfGlobalVar(globalVar);
jsonObject["len"] = length(globalVar);
jsonObject["value"] = valueOfGlobalVar(globalVar);
jsonObject["extra"] = descriptionOfGlobalVar(globalVar);
}
else
{
jsonObject["type"] = std::string("<unknown>");
jsonObject["len"] = (int)0;
jsonObject["value"] = json::Value(); // null
jsonObject["extra"] = json::Value(); // null
}
return jsonObject;
}
void enqueRefreshEvent()
{
ClientEvent refreshEvent(client_events::kWorkspaceRefresh);
module_context::enqueClientEvent(refreshEvent);
}
void enqueRemovedEvent(const r::sexp::Variable& variable)
{
ClientEvent removedEvent(client_events::kWorkspaceRemove, variable.first);
module_context::enqueClientEvent(removedEvent);
}
void enqueAssignedEvent(const r::sexp::Variable& variable)
{
// get object info
json::Value objInfo = jsonValueForGlobalVar(variable.first);
// enque event
ClientEvent assignedEvent(client_events::kWorkspaceAssign, objInfo);
module_context::enqueClientEvent(assignedEvent);
}
// last save action.
// NOTE: we don't persist this (or the workspace dirty state) during suspends in
// server mode. this means that if you are ever suspended then you will always
// end up with a 'dirty' workspace. not a big deal considering how infrequently
// quit occurs in server mode.
// TODO: this now affects switching projects after a suspend. we should try
// to figure out how to preserve dirty state of the workspace accross suspend
int s_lastSaveAction = r::session::kSaveActionAsk;
void enqueSaveActionChanged()
{
json::Object saveAction;
saveAction["action"] = s_lastSaveAction;
ClientEvent event(client_events::kSaveActionChanged, saveAction);
module_context::enqueClientEvent(event);
}
void checkForSaveActionChanged()
{
// compute current save action
int currentSaveAction = r::session::imageIsDirty() ?
module_context::saveWorkspaceAction() :
r::session::kSaveActionNoSave;
// compare and fire event if necessary
if (s_lastSaveAction != currentSaveAction)
{
s_lastSaveAction = currentSaveAction;
enqueSaveActionChanged();
}
}
// detect changes in the environment by inspecting the list of variable
// names as well as the SEXP pointers (a new pointer implies a mutation of
// an object)
class GlobalEnvironmentMonitor : boost::noncopyable
{
public:
GlobalEnvironmentMonitor()
: initialized_(false)
{
}
void reset()
{
initialized_ = false;
lastEnv_.clear();
}
void checkForChanges()
{
// get the current environment
std::vector<r::sexp::Variable> currentEnv ;
listEnvironment(¤tEnv);
// force refresh event the first time
if (!initialized_)
{
enqueRefreshEvent();
initialized_ = true;
}
// if there are changes
else if (currentEnv != lastEnv_)
{
// optimize for empty currentEnv (user reset workspace) or empty
// lastEnv_ (startup) by just sending a single WorkspaceRefresh event
if (currentEnv.empty() || lastEnv_.empty())
{
enqueRefreshEvent();
}
else
{
// find deletes (all variable names in the previous environment but
// NOT in the current environment)
std::vector<Variable> removedVars ;
std::set_difference(lastEnv_.begin(), lastEnv_.end(),
currentEnv.begin(), currentEnv.end(),
std::back_inserter(removedVars),
boost::bind(
&GlobalEnvironmentMonitor::compareVarName,
this, _1, _2));
// fire removed event for deletes
std::for_each(removedVars.begin(),
removedVars.end(),
enqueRemovedEvent);
// find adds & assigns (all variable name/value combinations in the
// current environment but NOT in the previous environment)
std::vector<Variable> addedVars ;
std::set_difference(currentEnv.begin(), currentEnv.end(),
lastEnv_.begin(), lastEnv_.end(),
std::back_inserter(addedVars));
// fire assigned event for adds & assigns
std::for_each(addedVars.begin(),
addedVars.end(),
enqueAssignedEvent);
}
}
// set the "last environment" list to the current env
// note that the SEXP values within the currentEnv are not protected
// beyond the scope of this call. this is OK because we only reference
// the pointer values not the underlying R objects. if we want to be
// able to manipulate the SEXPs directly we'll need a static protection
// context so the objects are guaranteed to survive until the next call
lastEnv_ = currentEnv;
}
private:
void listEnvironment(std::vector<r::sexp::Variable>* pEnvironment)
{
// get the variables currently in the global environment (note this list
// is guaranteed to be sorted based on the behavior of R_lsInternal)
r::sexp::Protect rProtect;
r::sexp::listEnvironment(R_GlobalEnv, false, &rProtect, pEnvironment);
}
// helper to deterine whether two variables have the same name
bool compareVarName(const Variable& var1, const Variable& var2)
{
return var1.first < var2.first ;
}
private:
std::vector<r::sexp::Variable> lastEnv_;
bool initialized_ ;
};
// global environment monitor
GlobalEnvironmentMonitor s_globalEnvironmentMonitor;
void onClientInit()
{
// reset monitor and check for changes for brand new client
s_globalEnvironmentMonitor.reset();
s_globalEnvironmentMonitor.checkForChanges();
// enque save action changed
enqueSaveActionChanged();
}
void onDetectChanges(module_context::ChangeSource source)
{
// check global environment
s_globalEnvironmentMonitor.checkForChanges();
// check for save action changed
checkForSaveActionChanged();
}
} // anonymous namespace
Error initialize()
{
// subscribe to events
using boost::bind;
using namespace session::module_context;
events().onClientInit.connect(bind(onClientInit));
events().onDetectChanges.connect(bind(onDetectChanges, _1));
// register handlers
ExecBlock initBlock ;
initBlock.addFunctions()
(bind(registerRBrowseFileHandler, handleRBrowseEnv))
(bind(sourceModuleRFile, "SessionWorkspace.R"));
return initBlock.execute();
}
} // namepsace workspace
} // namespace modules
} // namesapce session