-
Notifications
You must be signed in to change notification settings - Fork 0
/
manageR.py
5649 lines (5220 loc) · 243 KB
/
manageR.py
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
This file is part of manageR
Copyright (C) 2008-9 Carson J. Q. Farmer
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public Licence as published by the Free Software
Foundation; either version 2 of the Licence, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public Licence for more
details.
You should have received a copy of the GNU General Public Licence along with
this program (see LICENSE file in install directory); if not, write to the Free
Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
Portions of the console and EditR window, as well as several background
funtions are based on the Sandbox python gui of Mark Summerfield.
Copyright (C) 2007-9 Mark Summerfield. All rights reserved.
Released under the terms of the GNU General Public License.
The plugins functinality is based largely on the PostGisTools plugin of Mauricio de Paulo.
Copyright (C) 2009 Mauricio de Paulo. All rights reserved.
Released under the terms of the GNU General Public License.
manageR makes extensive use of rpy2 (Laurent Gautier) to communicate with R.
Copyright (C) 2008-9 Laurent Gautier.
Rpy2 may be used under the terms of the GNU General Public License.
'''
import os, re, sys, platform, base64
from xml.dom import minidom
import resources
# from multiprocessing import Process, Queue
from PyQt4.QtCore import (PYQT_VERSION_STR, QByteArray, QDir, QEvent,
QFile, QFileInfo, QIODevice, QPoint, QProcess, QRegExp, QObject,
QSettings, QString, QT_VERSION_STR, QTextStream, QThread, QRect,
QTimer, QUrl, QVariant, Qt, SLOT, SIGNAL, QStringList, QMimeData,
QEventLoop)
from PyQt4.QtNetwork import QHttp
from PyQt4.QtGui import (QAction, QApplication, QButtonGroup, QCheckBox,
QColor, QColorDialog, QComboBox, QCursor, QDesktopServices,
QDialog, QDialogButtonBox, QFileDialog, QFont, QFontComboBox,
QFontMetrics, QGridLayout, QHBoxLayout, QIcon, QInputDialog,
QKeySequence, QLabel, QLineEdit, QListWidget, QMainWindow,
QMessageBox, QPixmap, QPushButton, QRadioButton, QGroupBox,
QRegExpValidator, QShortcut, QSpinBox, QSplitter, QDirModel,
QSyntaxHighlighter, QTabWidget, QTextBrowser, QTextCharFormat,
QTextCursor, QTextDocument, QTextEdit, QPlainTextEdit, QToolTip,
QVBoxLayout, QPainter, QDoubleSpinBox, QMouseEvent,
QWidget, QDockWidget, QToolButton, QSpacerItem, QSizePolicy,
QPalette, QSplashScreen, QTreeWidget, QTreeWidgetItem, QFrame,
QListView, QTableWidget, QTableWidgetItem, QHeaderView, QMenu,
QAbstractItemView, QTextBlockUserData, QTextFormat, QClipboard,)
try:
from qgis.core import *
except ImportError:
pass
try:
import rpy2
import rpy2.robjects as robjects
import rpy2.rlike.container as rlc
# import rpy2.rinterface as rinterface
except ImportError:
QMessageBox.warning(None , "manageR", "Unable to load manageR: Unable to load required package rpy2."
+ "\nPlease ensure that both R, and the corresponding version of Rpy2 are correctly installed.")
__license__ = """<font color=green>\
Copyright © 2008-9 Carson J. Q. Farmer. All rights reserved.</font>
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation, version 2 of the License, or version 3 of the
License or (at your option) any later version.
This program is distributed in the hope that it will be useful, but
<i>without any warranty</i>; without even the implied warranty of
<i>merchantability</i> or <i>fitness for a particular purpose</i>.
See the <a href="http://www.gnu.org/licenses/">GNU General Public
License</a> for more details."""
KEYWORDS = ["break", "else", "for", "if", "in", "next", "repeat",
"return", "switch", "try", "while", "print", "return",
"not", "library", "attach", "detach", "ls", "as", "summary",
"plot", "hist", "lines", "points", "require", "load"]
BUILTINS = ["array", "character", "complex", "data.frame", "double",
"factor", "function", "integer", "list", "logical",
"matrix", "numeric", "vector"]
CONSTANTS = ["Inf", "NA", "NaN", "NULL", "TRUE", "FALSE"]
VECTORTYPES = ["SpatialPointsDataFrame",
"SpatialPolygonsDataFrame",
"SpatialLinesDataFrame"]
RASTERTYPES = ["SpatialGridDataFrame",
"SpatialPixelsDataFrame"]
Config = {}
CAT = QStringList() # Completions And Tooltips
Libraries = []
def welcomeString(version, isStandalone):
string = QString("Welcome to manageR %s\n" % version)
if not isStandalone:
string.append("QGIS interface to the R statistical analysis program\n")
string.append("Copyright (C) 2009-2010 Carson J. Q. Farmer\n")
string.append("Licensed under the terms of GNU GPL 2\n")
string.append("manageR is free software; ")
string.append("you can redistribute it and/or modify it under the terms")
string.append("of the GNU General Public License as published by the Free")
string.append("Software Foundation; either version 2 of the License, or")
string.append("(at your option) any later version.")
string.append("Currently running %s\n" % robjects.r.version[12][0])
return string
CURRENTDIR = unicode(os.path.abspath( os.path.dirname(__file__)))
def loadConfig():
def setDefaultString(name, default):
value = settings.value("manageR/%s" % (name)).toString()
if value.isEmpty():
value = default
Config[name] = value
settings = QSettings()
for name in ("window", "console"):
Config["%swidth" % name] = settings.value("manageR/%swidth" % name,
QVariant(QApplication.desktop()
.availableGeometry().width() / 2)).toInt()[0]
Config["%sheight" % name] = settings.value("manageR/%sheight" % name,
QVariant(QApplication.desktop()
.availableGeometry().height() / 2)).toInt()[0]
Config["%sy" % name] = settings.value("manageR/%sy" % name,
QVariant(0)).toInt()[0]
Config["toolbars"] = settings.value("manageR/toolbars").toByteArray()
Config["consolex"] = settings.value("manageR/consolex",
QVariant(0)).toInt()[0]
Config["windowx"] = settings.value("manageR/windowx",
QVariant(QApplication.desktop()
.availableGeometry().width() / 2)).toInt()[0]
Config["remembergeometry"] = settings.value("manageR/remembergeometry",
QVariant(True)).toBool()
Config["useraster"] = settings.value("manageR/useraster",
QVariant(False)).toBool()
setDefaultString("newfile", "")
setDefaultString("consolestartup", "")
Config["backupsuffix"] = settings.value("manageR/backupsuffix",
QVariant(".bak")).toString()
Config["beforeinput"] = settings.value("manageR/beforeinput",
QVariant(">")).toString()
Config["afteroutput"] = settings.value("manageR/afteroutput",
QVariant("+")).toString()
Config["setwd"] = settings.value("manageR/setwd", QVariant(".")).toString()
Config["findcasesensitive"] = settings.value("manageR/findcasesensitive",
QVariant(False)).toBool()
Config["findwholewords"] = settings.value("manageR/findwholewords",
QVariant(False)).toBool()
Config["tabwidth"] = settings.value("manageR/tabwidth",
QVariant(4)).toInt()[0]
Config["fontfamily"] = settings.value("manageR/fontfamily",
QVariant("Bitstream Vera Sans Mono")).toString()
Config["fontsize"] = settings.value("manageR/fontsize",
QVariant(10)).toInt()[0]
for name, color, bold, italic in (
("normal", "#000000", False, False),
("keyword", "#000080", True, False),
("builtin", "#0000A0", False, False),
("constant", "#0000C0", False, False),
("delimiter", "#0000E0", False, False),
("comment", "#007F00", False, True),
("string", "#808000", False, False),
("number", "#924900", False, False),
("error", "#FF0000", False, False),
("assignment", "#50621A", False, False),
("syntax", "#FF0000", False, True)):
Config["%sfontcolor" % name] = settings.value(
"manageR/%sfontcolor" % name, QVariant(color)).toString()
if name == "syntax":
Config["%sfontunderline" % name] = settings.value(
"manageR/%sfontunderline" % name, QVariant(bold)).toBool()
else:
Config["%sfontbold" % name] = settings.value(
"manageR/%sfontbold" % name, QVariant(bold)).toBool()
Config["%sfontitalic" % name] = settings.value(
"manageR/%sfontitalic" % name, QVariant(italic)).toBool()
Config["backgroundcolor"] = settings.value("manageR/backgroundcolor",
QVariant("#FFFFFF")).toString()
Config["delay"] = settings.value("manageR/delay",
QVariant(500)).toInt()[0]
Config["minimumchars"] = settings.value("manageR/minimumchars",
QVariant(3)).toInt()[0]
Config["enablehighlighting"] = settings.value("manageR/enablehighlighting",
QVariant(True)).toBool()
Config["enableautocomplete"] = settings.value("manageR/enableautocomplete",
QVariant(True)).toBool()
Config["bracketautocomplete"] = settings.value("manageR/bracketautocomplete",
QVariant(True)).toBool()
def saveConfig():
settings = QSettings()
for key, value in Config.items():
settings.setValue("manageR/%s" % (key), QVariant(value))
def addLibraryCommands(library):
if Config["enableautocomplete"]:
if not library in Libraries:
Libraries.append(library)
info = robjects.r('lsf.str("package:%s")' % (library))
info = QString(unicode(info)).replace(", \n ", ", ")
items = info.split('\n')
for item in items:
CAT.append(item)
def isLibraryLoaded(package="sp"):
return robjects.r("require(%s)" % (package))[0]
def listDataSets(package):
import re
isLibraryLoaded(package)
rdata = robjects.r["data"]
data = rdata(package=package).rx2('results')
# Get all data sets from R, this might be listing in subset (data set) format
data_sets = [data.rx(row_i, True)[2] for row_i in range(1, data.nrow + 1)]
# Get only unique values
data_sets_unique = set()
for i, data_set in enumerate(data_sets):
match = re.split('[()]', data_set)
if len(match) > 1:
data_sets_unique.add(match[1])
else:
data_sets_unique.add(data_set)
return list(data_sets_unique)
# This is used whenever we check for sp objects in manageR
def currentRObjects():
try:
ls_ = robjects.conversion.ri2py(
robjects.rinterface.globalEnv.get('ls',wantFun=True))
class_ = robjects.conversion.ri2py(
robjects.rinterface.globalEnv.get('class',wantFun=True))
dev_list_ = robjects.conversion.ri2py(
robjects.rinterface.globalEnv.get('dev.list',wantFun=True))
getwd_ = robjects.conversion.ri2py(
robjects.rinterface.globalEnv.get('getwd',wantFun=True))
except:
ls_ = robjects.r.get('ls', mode='function')
class_ = robjects.r.get('class', mode='function')
dev_list_ = robjects.r.get('dev.list' , mode='function')
getwd_ = robjects.r.get('getwd' , mode='function')
layers = {}
graphics = {}
for item in ls_():
check = class_(robjects.r[item])[0]
layers[unicode(item)] = check
if not unicode(item) in CAT:
CAT.append(unicode(item))
try:
# this is throwing exceptions...
graphics = dict(zip(list(dev_list_()),
list(dev_list_().names)))
except:
graphics = {}
cwd = getwd_()[0]
return (layers, graphics, cwd)
original = sys.stdout
class OutputCatcher(QObject):
def __init__(self, parent=None):
QObject.__init__(self, parent)
self.data = ''
def write(self, stuff):
self.data += stuff
#if len(self.data) > 80*100:
#self.get_and_clean_data()
def get_and_clean_data(self, emit=True):
tmp = self.data
self.clear()
#original.write(tmp)
if emit:
self.emit(SIGNAL("output(QString)"),
QString(tmp.decode('utf8')))
QApplication.processEvents()
return tmp
def flush(self):
pass
def clear(self):
self.data = ''
sys.stdout = OutputCatcher()
class HelpDialog(QDialog):
def __init__(self, version, parent=None):
super(HelpDialog, self).__init__(parent)
self.setAttribute(Qt.WA_GroupLeader)
self.setAttribute(Qt.WA_DeleteOnClose)
browser = QTextBrowser()
browser.setOpenExternalLinks(True)
browser.setHtml(
u"""
<center><h2>manageR %s documentation</h2>
<h3>Interface to the R statistical programming environment</h3>
<h4>Copyright © 2009 Carson J.Q. Farmer
<br/>[email protected]
<br/><a href='http://www.ftools.ca/manageR'>www.ftools.ca/manageR</a></h4></center>
<h4>Description:</h4>
<b>manageR</b> adds comprehensive statistical capabilities to <b>Quantum GIS</b> by
loosely coupling <b>QGIS</b> with the R statistical programming environment.
<h4>Features:</h4>
<ul><li>Perform complex statistical analysis functions on raster, vector and spatial database formats</li>
<li>Use the R statistical environment to graph, plot, and map spatial and aspatial data from within <b>QGIS</b></li>
<li>Export R (sp) vector layers directly to <b>QGIS</b> map canvas as <b>QGIS</b> vector layers</li>
<li>Read <b>QGIS</b> vector layers directly from map canvas as R (sp) vector layers, allowing analysis to be carried out on any vector format supported by <b>QGIS</b></li>
<li>Perform all available R commands from within <b>QGIS</b>, including multi-line commands</li>
<li>Visualise R commands clearly and cleanly using any one of the four included syntax highlighting themes</li>
<li>Create, edit, and save R scripts for complex statistical and computational operations</li></ul>
<h4>Usage:</h4>
<ul><li><tt>Ctrl+L</tt> : Import selected <b>l</b>ayer</li>
<li><tt>Ctrl+T</tt> : Import attribute <b>t</b>able of selected layer</li>
<li><tt>Ctrl+M</tt> : Export R layer to <b>m</b>ap canvas</li>
<li><tt>Ctrl+D</tt> : Export R layer to <b>d</b>isk</li>
<li><tt>Ctrl+Return</tt> : Send (selected) commands from <b>EditR</b> window to
<b>manageR</b> console</li></ul>
<h4>Details:</h4>
<p>
Use <tt>Ctrl+L</tt> to import the currently selected layer in the <b>QGIS</b>
layer list into the <b>manageR</b> environment. To import only the attribute
table of the selected layer, use <tt>Ctrl+T</tt>. Exporting R layers
from the <b>manageR</b> environment is done via <tt>Ctrl-M</tt> and <tt>Ctrl-D</tt>,
where M signifies exporting to the map canvas, and D signifies exporting to disk. Each
of these commands are also available via the <b>Actions</b> toolbar in the <b>manageR</b>
console.
</p>
<p>
The <b>manageR</b> console is also equipped with several additional tools to help manage the R
environment. These tools include a <b>Workspace</b> manager, a <b>Graphic Devices</b> manager,
a <b>Command History</b> manager, and a <b>Working Directory</b> manager.
</p>
<p>
Use <tt>Ctrl+R</tt> to send commands from an <b>EditR</b> window to the <b>manageR</b>
console. If an <b>EditR</b> window contains selected text, only this text will be sent
to the <b>manageR</b> console, otherwise, all text is sent. The <b>EditR</b> window
also contains tools for creating, loading, editing, and saving R scripts. The suite of
available tools is outlined in detail in the <b>Key bindings</b> section.
</p>
<h4>Additional tools:</h4>
<p>
<i>Autocompletion</i><br>
If enabled, command completion suggestions are automatically shown after %d seconds
based on the current work. This can also be manually activated using <b>Ctrl+Space</b>.
In addition, a tooltip will appear if one is available for the selected command.
Autocompletion and tooltips are available for R functions and commands within
libraries that are automatically loaded by R, or <b>manageR</b>,
as well as any additional libraries loaded after the <b>manageR</b> session has started.
(This makes loading libraries with many built-in functions or additional libraries slightly
longer than in a normal R session). It is possible to turn off autocompletion (and tooltips)
by unchecking File\N{RIGHTWARDS ARROW}Configure\N{RIGHTWARDS ARROW}
General tab\N{RIGHTWARDS ARROW}Enable autocompletion.
</p>
<p>
<i>Find and Replace</i><br>
A Find and Replace toolbar is available for both the <b>manageR</b> console and <b>EditR</b>
window (the replace functionality is only available in <b>EditR</b>). When activated (see
<b>Key Bindings</b> section below), if any text is selected in the parent dialog, this text
will be placed in the 'Find toolbar' for searching. To search for
the next occurrence of the text or phrase in the toolbar, type <tt>Enter</tt>
or click the 'Next' button. Conversely, click the 'Previous' button to search backwards. To
replace text as it is found, simply type the replacement text in the 'Replace' line edit and
click 'Replace'. To replace all occurrences of the found text, click 'Replace all'. All
searches can be refined by using the 'Case sensitive' and 'Whole words' check boxes.
</p>
<p>
<i>Workspace Manager</i></i><br>
The variables table stores the name and type of all currently loaded variables in your global
R environment (globalEnv). From here, it is possible to remove, save, and load R variables, as
well as export R variables to file, or the <b>QGIS</b> map canvas (when a Spatial*Data Frames is selected).
</p>
<p>
<i>Graphic Device Manager</i><br>
The graphic devices table stores the ID and device type of all current R graphic devices. From here,
it is possible to refresh the list of graphic devices, create a new empty graphic window, and remove
existing devices. In addition, it is possible to export the selected graphic device to file in both raster
and vector formats.
</p>
<p>
<i>Command History Manager</i><br>
The command history stores a list of all previously executed commands (including commands loaded from a
.RHistory file). From here it is possible to insert a command into the <b>manageR</b> console by
right clicking and selecting 'insert' in the popup menu. Similarly, multiple commands can be selected,
copied, or cleared using the popup menu. Individual commands can be selected or unselected simply by
clicking on them using the left mouse button. To run all selected commands, right click anywhere within
the command history widget, and select run from the popup menu. Each of these actions are also available
via the icons at the top of the command history widget.
</p>
<p>
<i>Working Directory Manager</i><br>
The working directory widget is a simple toolbar to help browse to different working directories, making it
relatively simple to change the current R working directory.
</p>
<p>
<i>Startup and New Script Commands</i><br>
Additional tools include the ability to specify startup commands to be run whenever <b>manageR</b>
is started (see File\N{RIGHTWARDS ARROW}Configure\N{RIGHTWARDS ARROW}At Startup),
as well as a tab to specify the text/commands to be included at the top of all new R scripts (see
File\N{RIGHTWARDS ARROW}Configure\N{RIGHTWARDS ARROW}On New File).
</p>
<p>
<i>Analysis</i><br>
<b>manageR</b> supports simple plugins which help to streamline tedious R functions by providing a
plugin framework for creating simple graphical user interfaces (GUI) to commonly used R functions.
These functions can be specified using an XML ('tools.xml') file stored in the <b>manageR</b>
installation folder (%s). The format of the XML file should be as follows:
<font color=green><i>
<pre><?xml version="1.0"?>
<manageRTools>
<RTool name="Insert random R commands" query="|1|">
<Parameter label="R commands:" type="textEdit" default="ls()" notnull="true"/>
</RTool>
<manageRTools></i></font>
</pre>
where each RTool specifies a unique R function. In the above example, the GUI will consist of a simple
dialog with a text editing region to input user-defined R commands, and an OK and CLOSE button. When
OK is clicked, the R commands in the text editing region will be run, and when CLOSE is clicked,
the dialog will be closed. In the example above, query is set to <tt>|1|</tt>, which means take the
output from the first parameter, and place here. In other words, in this case the entire query is
equal to whatever is input into the text editing region (default here is <tt>ls()</tt>). Other GUI
parameters that may be entered include:
<ul>
<li>comboBox: Drop-down list box</li>
<li>doubleSpinBox: Widget for entering numerical values</li>
<li>textEdit: Text editing region</li>
<li>spComboBox: Combobox widget for displaying a dropdown list of variables (e.g. numeric,
data.frame, Spatial*DataFrame)</li>
<li>spListWidget: Widget for displaying lists of variables (e.g. numeric, data.frame, Spatial*DataFrame)</li>
<li>helpString: Non-graphical parameter that is linked to the help button on the dialog
(can use 'topic:help_topic' or custom html based help text)</li></ul>
Default values for all of the above GUI parameters can be specified in the XML file, using semi-colons
to separate multiple options. For the spComboBox, the default string should specify the type(s) of
variables to display (e.g. numeric;data,frame;SpatialPointsDataFrame).
<b>manageR</b> comes with several default R GUI functions which can be used as examples for creating
custom R functions.
</p>
<h4>Key bindings:</h4>
<ul>
<li><tt>\N{UPWARDS ARROW}</tt> : In the <b>manageR</b> console, show the previous command
from the command history. In the <b>EditR</b> windows, move up one line.
<li><tt>\N{DOWNWARDS ARROW}</tt> : In the <b>manageR</b> console, show the next command
from the command history. In the <b>EditR</b> windows, move down one line.
<li><tt>\N{LEFTWARDS ARROW}</tt> : Move the cursor left one character
<li><tt>Ctrl+\N{LEFTWARDS ARROW}</tt> : Move the cursor left one word
<li><tt>\N{RIGHTWARDS ARROW}</tt> : Move the cursor right one character
<li><tt>Ctrl+\N{RIGHTWARDS ARROW}</tt> : Move the cursor right one word
<li><tt>Ctrl+]</tt> : Indent the selected text (or the current line) by %d spaces
<li><tt>Ctrl+[</tt> : Unindent the selected text (or the current line) by %d spaces
<li><tt>Ctrl+A</tt> : Select all the text
<li><tt>Backspace</tt> : Delete the character to the left of the cursor
<li><tt>Ctrl+C</tt> : In the <b>manageR</b> console, if the cursor is in the command line, clear
current command(s), otherwise copy the selected text to the clipboard (same for <b>EditR</b>
windows.
<li><tt>Delete</tt> : Delete the character to the right of the cursor
<li><tt>End</tt> : Move the cursor to the end of the line
<li><tt>Ctrl+End</tt> : Move the cursor to the end of the file
<li><tt>Ctrl+Return</tt> : In an <b>EditR</b> window, execute the (selected) code/text
<li><tt>Ctrl+F</tt> : Pop up the Find toolbar
<li><tt>Ctrl+R</tt> : In an <b>EditR</b> window, pop up the Find and Replace toolbar
<li><tt>Home</tt> : Move the cursor to the beginning of the line
<li><tt>Ctrl+Home</tt> : Move the cursor to the beginning of the file
<li><tt>Ctrl+K</tt> : Delete to the end of the line
<li><tt>Ctrl+H</tt> : Pop up the 'Goto line' dialog
<li><tt>Ctrl+N</tt> : Open a new editor window
<li><tt>Ctrl+O</tt> : Open a file open dialog to open an R script
<li><tt>Ctrl+Space</tt> : Pop up a list of possible completions for
the current word. Use the up and down arrow keys and the page up and page
up keys (or the mouse) to navigate; click <tt>Enter</tt> to accept a
completion or <tt>Esc</tt> to cancel.
<li><tt>PageUp</tt> : Move up one screen
<li><tt>PageDown</tt> : Move down one screen
<li><tt>Ctrl+Q</tt> : Terminate manageR; prompting to save any unsaved changes
for every <b>EditR</b> window for which this is necessary. If the user cancels
any save unsaved changes message box, manageR will not terminate.
<li><tt>Ctrl+S</tt> : Save the current file
<li><tt>Ctrl+V</tt> : Paste the clipboard's text
<li><tt>Ctrl+W</tt> : Close the current file; prompting to save any unsaved
changes if necessary
<li><tt>Ctrl+X</tt> : Cut the selected text to the clipboard
<li><tt>Ctrl+Z</tt> : Undo the last editing action
<li><tt>Ctrl+Shift+Z</tt> : Redo the last editing action
<li><tt>Ctrl+L</tt> : Import selected <b>l</b>ayer</li>
<li><tt>Ctrl+T</tt> : Import attribute <b>t</b>able of selected layer</li>
<li><tt>Ctrl+M</tt> : Export R layer to <b>m</b>ap canvas</li>
<li><tt>Ctrl+D</tt> : Export R layer to <b>d</b>isk</li>
<li><tt>Ctrl+Return</tt> : Send (selected) commands from <b>EditR</b> window to
<b>manageR</b> console</li>
</ul>
Hold down <tt>Shift</tt> when pressing movement keys to select the text moved over.
<br>
Thanks to Agustin Lobo for extensive testing and bug reporting.
Press <tt>Esc</tt> to close this window.
""" % (version, Config["delay"], CURRENTDIR, #str(os.path.abspath( os.path.dirname(__file__))),
Config["tabwidth"], Config["tabwidth"]))
layout = QVBoxLayout()
layout.setMargin(0)
layout.addWidget(browser)
self.setLayout(layout)
self.resize(500, 500)
QShortcut(QKeySequence("Escape"), self, self.close)
self.setWindowTitle("manageR - Help")
def RLibraryError(library):
message = QString("Error: Unable to find R package '%s'.\n" % (library))
message.append("Please manually install the '%s' package in R via " % (library))
message.append("install.packages()")
return message
class RFinder(QWidget):
def __init__(self, parent, document):
QWidget.__init__(self, parent)
# initialise standard settings
self.document = document
grid = QGridLayout(self)
self.edit = QLineEdit(self)
font = QFont(Config["fontfamily"], Config["fontsize"])
font.setFixedPitch(True)
find_label = QLabel("Find:")
find_label.setMaximumWidth(50)
self.edit.setFont(font)
self.edit.setToolTip("Find text")
self.next = QToolButton(self)
self.next.setText("Next")
self.next.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
self.next.setIcon(QIcon(":mActionNext.png"))
self.next.setToolTip("Find next")
self.previous = QToolButton(self)
self.previous.setToolTip("Find previous")
self.previous.setText("Previous")
self.previous.setIcon(QIcon(":mActionPrevious.png"))
self.previous.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
self.whole_words = QCheckBox()
self.whole_words.setText("Whole words")
self.case_sensitive = QCheckBox()
self.case_sensitive.setText("Case sensitive")
#find_horiz = QHBoxLayout()
grid.addWidget(find_label,1,0,1,1)
#find_horiz.addWidget(find_label)
grid.addWidget(self.edit, 1,1,1,2)
#find_horiz.addWidget(self.edit)
grid.addWidget(self.next, 1,3,1,1)
#find_horiz.addWidget(self.previous)
grid.addWidget(self.previous, 1,4,1,1)
#find_horiz.addWidget(self.next)
grid.addWidget(self.whole_words, 0,3,1,1)
grid.addWidget(self.case_sensitive, 0,4,1,1)
#grid.addLayout(find_horiz, 1, 0, 1, 3)
self.replace_label = QLabel("Replace:")
self.replace_label.setMaximumWidth(50)
self.replace_edit = QLineEdit(self)
self.replace_edit.setFont(font)
self.replace_edit.setToolTip("Replace text")
self.replace = QToolButton(self)
self.replace.setText("Replace")
self.replace.setToolTip("Replace text")
self.replace_all = QToolButton(self)
self.replace_all.setToolTip("Replace all")
self.replace_all.setText("Replace all")
#replace_horiz = QHBoxLayout()
grid.addWidget(self.replace_label, 2, 0, 1, 1)
#replace_horiz.addWidget(self.replace_label)
grid.addWidget(self.replace_edit, 2, 1, 1, 2)
#replace_horiz.addWidget(self.replace_edit)
grid.addWidget(self.replace, 2, 3, 1, 1)
#replace_horiz.addWidget(self.replace)
grid.addWidget(self.replace_all, 2, 4, 1, 1)
#replace_horiz.addWidget(self.replace_all)
#grid.addLayout(replace_horiz, 2, 0, 1, 3)
self.setFocusProxy(self.edit)
self.setVisible(False)
self.connect(self.next, SIGNAL("clicked()"), self.findNext)
self.connect(self.previous, SIGNAL("clicked()"), self.findPrevious)
self.connect(self.replace, SIGNAL("clicked()"), self.replaceNext)
self.connect(self.edit, SIGNAL("returnPressed()"), self.findNext)
self.connect(self.replace_all, SIGNAL("clicked()"), self.replaceAll)
def find(self, forward):
if not self.document:
return False
text = QString(self.edit.text())
found = False
if text == "":
return False
else:
flags = QTextDocument.FindFlag()
if self.whole_words.isChecked():
flags = (flags|QTextDocument.FindWholeWords)
if self.case_sensitive.isChecked():
flags = (flags|QTextDocument.FindCaseSensitively)
if not forward:
flags = (flags|QTextDocument.FindBackward)
fromPos = self.document.toPlainText().length() - 1
else:
fromPos = 0
if not self.document.find(text, flags):
cursor = QTextCursor(self.document.textCursor())
selection = cursor.hasSelection()
if selection:
start = cursor.selectionStart()
end = cursor.selectionEnd()
else:
pos = cursor.position()
cursor.setPosition(fromPos)
self.document.setTextCursor(cursor)
if not self.document.find(text, flags):
if selection:
cursor.setPosition(start, QTextCursor.MoveAnchor)
cursor.setPosition(end, QTextCursor.KeepAnchor)
else:
cursor.setPosition(pos)
self.document.setTextCursor(cursor)
return False
elif selection:
cursor = QTextCursor(self.document.textCursor())
if start == cursor.selectionStart():
return False
return True
def findNext(self):
return self.find(True)
def findPrevious(self):
return self.find(False)
def showReplace(self):
self.replace_edit.setVisible(True)
self.replace.setVisible(True)
self.replace_all.setVisible(True)
self.replace_label.setVisible(True)
def hideReplace(self):
self.replace_edit.setVisible(False)
self.replace.setVisible(False)
self.replace_all.setVisible(False)
self.replace_label.setVisible(False)
def replaceNext(self):
cursor = QTextCursor(self.document.textCursor())
selection = cursor.hasSelection()
if selection:
text = QString(cursor.selectedText())
current = QString(self.edit.text())
replace = QString(self.replace_edit.text())
if text == current:
cursor.insertText(replace)
cursor.select(QTextCursor.WordUnderCursor)
else:
return self.findNext()
self.findNext()
return True
def replaceAll(self):
while self.findNext():
self.replaceNext()
self.replaceNext()
def keyPressEvent(self, e):
if e.key() == Qt.Key_Escape:
self.document.setFocus()
class LibrarySplitter(QSplitter):
def __init__(self, parent):
super(LibrarySplitter, self).__init__(parent)
robjects.r("""make.packages.html()""")
host = "localhost"
port = robjects.r('tools:::httpdPort')[0]
home = "/doc/html/packages.html"
self.home = home
paths = QStringList(os.path.join(CURRENTDIR, "icons"))
self.setOrientation(Qt.Vertical)
self.setFrameStyle(QFrame.StyledPanel|QFrame.Sunken)
monofont = QFont(Config["fontfamily"], Config["fontsize"])
self.table = QTableWidget(0, 4, self)
self.table.setFont(monofont)
labels = QStringList()
labels.append("Loaded")
labels.append("Package")
labels.append("Title")
labels.append("Path")
self.table.setHorizontalHeaderLabels(labels)
self.table.setShowGrid(True)
self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
self.table.setSelectionMode(QAbstractItemView.SingleSelection)
self.table.setAlternatingRowColors(True)
self.viewer = HtmlViewer(self, host, port, home, paths)
self.update_packages()
self.connect(self.table, SIGNAL("itemChanged(QTableWidgetItem*)"), self.load_package)
self.connect(self.table, SIGNAL("itemDoubleClicked(QTableWidgetItem*)"), self.show_package)
sys.stdout.get_and_clean_data()
def show_package(self, item):
row = item.row()
tmp = self.table.item(row, 1)
package = tmp.text()
home = QUrl(self.home)
curr = QUrl("../../library/%s/html/00Index.html" % package)
self.viewer.setSource(home.resolved(curr))
def load_package(self, item):
mime = QMimeData()
row = item.row()
tmp = self.table.item(row, 1)
package = tmp.text()
if item.checkState() == Qt.Checked:
mime.setText("library(%s)" % package)
else:
mime.setText("detach('package:%s')" % package)
MainWindow.Console.editor.moveToEnd()
MainWindow.Console.editor.cursor.movePosition(
QTextCursor.StartOfBlock, QTextCursor.KeepAnchor)
MainWindow.Console.editor.cursor.removeSelectedText()
MainWindow.Console.editor.cursor.insertText(
MainWindow.Console.editor.currentPrompt)
MainWindow.Console.editor.insertFromMimeData(mime)
MainWindow.Console.editor.entered()
def update_packages(self):
library_ = robjects.r.get('library', mode='function')
packages_ = robjects.r.get('.packages', mode='function')
loaded = list(packages_())
packages = list(library_()[1])
length = len(packages)
self.table.clearContents()
sys.stdout.get_and_clean_data(False)
#self.table.setRowCount(length/3)
package_list = []
for i in range(length/3):
package = unicode(packages[i])
if not package in package_list:
package_list.append(package)
self.table.setRowCount(len(package_list))
item = QTableWidgetItem("Loaded")
item.setFlags(
Qt.ItemIsUserCheckable|Qt.ItemIsEnabled|Qt.ItemIsSelectable)
if package in loaded:
item.setCheckState(Qt.Checked)
else:
item.setCheckState(Qt.Unchecked)
self.table.setItem(i, 0, item)
item = QTableWidgetItem(unicode(packages[i]))
item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsSelectable)
self.table.setItem(i, 1, item)
item = QTableWidgetItem(unicode(packages[i+(2*(length/3))]))
item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsSelectable)
self.table.setItem(i, 2, item)
item = QTableWidgetItem(unicode(packages[i+(length/3)]))
item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsSelectable)
self.table.setItem(i, 3, item)
self.table.resizeColumnsToContents()
class LibraryBrowser(QDialog):
def __init__(self, parent=None):
super(LibraryBrowser, self).__init__(parent)
#self.setAttribute(Qt.WA_GroupLeader)
#self.setAttribute(Qt.WA_DeleteOnClose)
layout = QVBoxLayout()
layout.setMargin(0)
splitter = LibrarySplitter(self)
layout.addWidget(splitter)
self.setLayout(layout)
QShortcut(QKeySequence("Escape"), self, self.close)
self.setWindowTitle("manageR - Library browser")
self.resize(500, 500)
class HtmlViewer(QWidget):
class PBrowser(QTextBrowser):
def __init__(self, parent, host, port, home, paths):
QTextBrowser.__init__(self, parent)
self.http = QHttp()
self.http.setHost(host, port)
home = QUrl(home)
self.base = home
self.html = QString()
self.setOpenLinks(True)
self.setSearchPaths(paths)
self.connect(self.http, SIGNAL(
"done(bool)"), self.getData)
self.anchor = QString()
self.setSource(home)
def setSource(self, url):
url = self.source().resolved(url)
QTextBrowser.setSource(self, url)
def loadResource(self, type, name):
ret = QVariant()
name.setFragment(QString())
if type == QTextDocument.HtmlResource:
loop = QEventLoop()
loop.connect(self.http, SIGNAL(
"done(bool)"), SLOT("quit()"))
self.http.get(name.toString())
loop.exec_(
QEventLoop.AllEvents | \
QEventLoop.WaitForMoreEvents)
data = QVariant(QString(self.html))
else:
fileName = QFileInfo(
name.toLocalFile()).fileName()
data = QTextBrowser.loadResource(
self, type, QUrl(fileName))
return data
def getData(self, error):
if error:
self.html = self.http.errorString()
else:
self.html = self.http.readAll()
def __init__(self, parent, host, port, home, paths):
super(HtmlViewer, self).__init__(parent)
robjects.r("""make.packages.html()""")
self.viewer = self.PBrowser(self, host, port, home, paths)
self.parent = parent
homeButton = QToolButton(self)
homeAction = QAction("&Home", self)
homeAction.setToolTip("Return to start page")
homeAction.setWhatsThis("Return to start page")
homeAction.setIcon(QIcon(":mActionHome.png"))
homeButton.setDefaultAction(homeAction)
homeAction.setEnabled(True)
homeButton.setAutoRaise(True)
backwardButton = QToolButton(self)
backwardAction = QAction("&Back", self)
backwardAction.setToolTip("Move to previous page")
backwardAction.setWhatsThis("Move to previous page")
backwardAction.setIcon(QIcon(":mActionBack.png"))
backwardButton.setDefaultAction(backwardAction)
backwardAction.setEnabled(False)
backwardButton.setAutoRaise(True)
forwardButton = QToolButton(self)
forwardAction = QAction("&Forward", self)
forwardAction.setToolTip("Move to next page")
forwardAction.setWhatsThis("Move to next page")
forwardAction.setIcon(QIcon(":mActionForward.png"))
forwardButton.setDefaultAction(forwardAction)
forwardAction.setEnabled(False)
forwardButton.setAutoRaise(True)
vert = QVBoxLayout(self)
horiz = QHBoxLayout()
horiz.addStretch()
horiz.addWidget(backwardButton)
horiz.addWidget(homeButton)
horiz.addWidget(forwardButton)
horiz.addStretch()
vert.addLayout(horiz)
vert.addWidget(self.viewer)
self.connect(self.viewer, SIGNAL("forwardAvailable(bool)"), forwardAction.setEnabled)
self.connect(self.viewer, SIGNAL("backwardAvailable(bool)"), backwardAction.setEnabled)
self.connect(homeAction, SIGNAL("triggered()"), self.home)
self.connect(backwardAction, SIGNAL("triggered()"), self.backward)
self.connect(forwardAction, SIGNAL("triggered()"), self.forward)
def home(self):
self.viewer.home()
def backward(self):
self.viewer.backward()
def forward(self):
self.viewer.forward()
def setSource(self, url):
self.viewer.setSource(url)
class RHighlighter(QSyntaxHighlighter):
Rules = []
Formats = {}
def __init__(self, parent=None, isConsole=False):
super(RHighlighter, self).__init__(parent)
self.parent = parent
if isinstance(self.parent, QPlainTextEdit):
self.setDocument(self.parent.document())
self.initializeFormats()
self.isConsole = isConsole
RHighlighter.Rules.append((QRegExp(
r"[a-zA-Z_]+[a-zA-Z_\.0-9]*(?=[\s]*[(])"), "keyword"))
RHighlighter.Rules.append((QRegExp(
"|".join([r"\b%s\b" % keyword for keyword in KEYWORDS])),
"keyword"))
RHighlighter.Rules.append((QRegExp(
"|".join([r"\b%s\b" % builtin for builtin in BUILTINS])),
"builtin"))
#RHighlighter.Rules.append((QRegExp(
#r"[a-zA-Z_\.][0-9a-zA-Z_\.]*[\s]*=(?=([^=]|$))"), "inbrackets"))
RHighlighter.Rules.append((QRegExp(
"|".join([r"\b%s\b" % constant
for constant in CONSTANTS])), "constant"))
RHighlighter.Rules.append((QRegExp(
r"\b[+-]?[0-9]+[lL]?\b"
r"|\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b"
r"|\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b"),
"number"))
RHighlighter.Rules.append((QRegExp(r"[\)\(]+|[\{\}]+|[][]+"),
"delimiter"))
RHighlighter.Rules.append((QRegExp(
r"[<]{1,2}\-"
r"|\-[>]{1,2}"
r"|=(?!=)"
r"|\$"
r"|\@"), "assignment"))
RHighlighter.Rules.append((QRegExp(
r"([\+\-\*/\^\:\$~!&\|=>@^])([<]{1,2}\-|\-[>]{1,2})"
r"|([<]{1,2}\-|\-[>]{1,2})([\+\-\*/\^\:\$~!&\|=<@])"
r"|([<]{3}|[>]{3})"
r"|([\+\-\*/\^\:\$~&\|@^])="
r"|=([\+\-\*/\^\:\$~!<>&\|@^])"
#r"|(\+|\-|\*|/|<=|>=|={1,2}|\!=|\|{1,2}|&{1,2}|:{1,3}|\^|@|\$|~){2,}"
),
"syntax"))
self.stringRe = QRegExp("(\'[^\']*\'|\"[^\"]*\")")
self.stringRe.setMinimal(True)
RHighlighter.Rules.append((self.stringRe, "string"))
RHighlighter.Rules.append((QRegExp(r"#.*"), "comment"))
self.multilineSingleStringRe = QRegExp(r"""'(?!")""")
self.multilineDoubleStringRe = QRegExp(r'''"(?!')''')
self.bracketBothExpression = QRegExp(r"[\(\)]")
self.bracketStartExpression = QRegExp(r"\(")
self.bracketEndExpression = QRegExp(r"\)")
@staticmethod
def initializeFormats():
baseFormat = QTextCharFormat()
baseFormat.setFontFamily(Config["fontfamily"])
baseFormat.setFontPointSize(Config["fontsize"])
for name in ("normal", "keyword", "builtin", "constant",
"delimiter", "comment", "string", "number", "error",
"assignment", "syntax"):
format = QTextCharFormat(baseFormat)
format.setForeground(
QColor(Config["%sfontcolor" % name]))
if name == "syntax":
format.setFontUnderline(Config["%sfontunderline" % name])
else:
if Config["%sfontbold" % name]:
format.setFontWeight(QFont.Bold)
format.setFontItalic(Config["%sfontitalic" % name])
RHighlighter.Formats[name] = format
format = QTextCharFormat(baseFormat)
if Config["assignmentfontbold"]:
format.setFontWeight(QFont.Bold)
format.setForeground(
QColor(Config["assignmentfontcolor"]))
format.setFontItalic(Config["%sfontitalic" % name])
RHighlighter.Formats["inbrackets"] = format
def highlightBlock(self, text):
NORMAL, MULTILINESINGLE, MULTILINEDOUBLE, ERROR = range(4)
INBRACKETS, INBRACKETSSINGLE, INBRACKETSDOUBLE = range(4,7)
textLength = text.length()
prevState = self.previousBlockState()
self.setFormat(0, textLength,
RHighlighter.Formats["normal"])
if text.startsWith("Error") and self.isConsole:
self.setCurrentBlockState(ERROR)
self.setFormat(0, textLength, RHighlighter.Formats["error"])
return
if (prevState == ERROR and self.isConsole and \
not (text.startsWith(Config["beforeinput"]) or text.startsWith("#"))):
self.setCurrentBlockState(ERROR)
self.setFormat(0, textLength, RHighlighter.Formats["error"])
return