File: rkworkplace.cpp

package info (click to toggle)
rkward 0.6.5-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 20,848 kB
  • ctags: 6,376
  • sloc: cpp: 40,537; xml: 7,871; makefile: 46; sh: 13
file content (1039 lines) | stat: -rw-r--r-- 34,629 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
/***************************************************************************
                          rkworkplace  -  description
                             -------------------
    begin                : Thu Sep 21 2006
    copyright            : (C) 2006-2016 by Thomas Friedrichsmeier
    email                : thomas.friedrichsmeier@kdemail.net
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include "rkworkplace.h"

#include <kparts/partmanager.h>
#include <kmessagebox.h>
#include <klocale.h>
#include <kiconloader.h>
#include <khbox.h>
#include <kvbox.h>
#include <kglobalsettings.h>
#include <kactioncollection.h>
#include <krun.h>
#include <kmimetype.h>
#include <kstandarddirs.h>

#include <QFileInfo>
#include <QCryptographicHash>

#include "detachedwindowcontainer.h"
#include "rkcommandeditorwindow.h"
#include "rkhtmlwindow.h"
#include "rkworkplaceview.h"
#include "rktoolwindowbar.h"
#include "rktoolwindowlist.h"
#include "../core/robject.h"
#include "../core/rcontainerobject.h"
#include "../core/robjectlist.h"
#include "../dataeditor/rkeditor.h"
#include "../dataeditor/rkeditordataframe.h"
#include "../robjectviewer.h"
#include "../settings/rksettingsmodulegeneral.h"
#include "../settings/rksettingsmodulecommandeditor.h"
#include "../rbackend/rinterface.h"
#include "../windows/rkwindowcatcher.h"
#include "../rbackend/rcommand.h"
#include "../misc/rkcommonfunctions.h"
#include "../rkglobals.h"
#include "../rkward.h"

#include "../debug.h"

// static
RKWorkplace *RKWorkplace::main_workplace = 0;

RKWorkplace::RKWorkplace (QWidget *parent) : QWidget (parent) {
	RK_TRACE (APP);
	RK_ASSERT (main_workplace == 0);

	main_workplace = this;
	_workspace_config = 0;
	window_placement_override = RKMDIWindow::AnyWindowState;

	/* Splitter setup contains heavy copying from Kate's katemdi! */
	KVBox *vbox = new KVBox (this);

	tool_window_bars[RKToolWindowList::Top] = new RKToolWindowBar (KMultiTabBar::Top, vbox);
	vert_splitter = new QSplitter (Qt::Vertical, vbox);
	vert_splitter->setOpaqueResize (KGlobalSettings::opaqueResize ());
	tool_window_bars[RKToolWindowList::Top]->setSplitter (vert_splitter);

	KHBox *hbox = new KHBox (vert_splitter);
	vert_splitter->setCollapsible (vert_splitter->indexOf (hbox), false);
	vert_splitter->setStretchFactor (vert_splitter->indexOf (hbox), 1);

	tool_window_bars[RKToolWindowList::Left] = new RKToolWindowBar (KMultiTabBar::Left, hbox);
	horiz_splitter = new QSplitter (Qt::Horizontal, hbox);
	horiz_splitter->setOpaqueResize (KGlobalSettings::opaqueResize ());
	tool_window_bars[RKToolWindowList::Left]->setSplitter (horiz_splitter);

	wview = new RKWorkplaceView (horiz_splitter);
	horiz_splitter->setCollapsible (horiz_splitter->indexOf (wview), false);
	horiz_splitter->setStretchFactor(horiz_splitter->indexOf (wview), 1);

	tool_window_bars[RKToolWindowList::Bottom] = new RKToolWindowBar (KMultiTabBar::Bottom, vbox);
	tool_window_bars[RKToolWindowList::Bottom]->setSplitter (vert_splitter);

	tool_window_bars[RKToolWindowList::Right] = new RKToolWindowBar (KMultiTabBar::Right, hbox);
	tool_window_bars[RKToolWindowList::Right]->setSplitter (horiz_splitter);

	KConfigGroup toolbar_config = KGlobal::config ()->group ("ToolwindowBars");
	for (int i = 0; i < TOOL_WINDOW_BAR_COUNT; ++i) tool_window_bars[i]->restoreSize (toolbar_config);

	// now add it all to this widget
	QVBoxLayout *box = new QVBoxLayout (this);
	box->setContentsMargins (0, 0, 0, 0);
	box->addWidget (vbox);

	history = new RKMDIWindowHistory (this);

	connect (RKWardMainWindow::getMain (), SIGNAL (aboutToQuitRKWard()), this, SLOT (saveSettings()));
}

RKWorkplace::~RKWorkplace () {
	RK_TRACE (APP);

	delete _workspace_config;
//	closeAll ();	// not needed, as the windows will autodelete themselves using QObject mechanism. Of course, closeAll () should be called *before* quitting.
}

QString workspaceConfigFileName (const KUrl &url) {
	QString base_name = QString (QCryptographicHash::hash (url.prettyUrl ().toUtf8 (), QCryptographicHash::Md5).toHex());
	return (KStandardDirs::locateLocal ("data", "rkward/workspace_config_" + base_name));
}

KConfigBase *RKWorkplace::workspaceConfig () {
	if (!_workspace_config) {
		RK_TRACE (APP);
		_workspace_config = new KConfig (workspaceConfigFileName (workspaceURL ()));
	}
	return _workspace_config;
}

QString RKWorkplace::portableUrl (const KUrl &url) {
	KUrl relative = KUrl::relativeUrl (workspaceURL (), url);
	relative.cleanPath ();
	return relative.prettyUrl ();
}

void RKWorkplace::setWorkspaceURL (const KUrl &url, bool keep_config) {
	RK_TRACE (APP);

	if (url != current_url) {
		current_url = url;
		if (keep_config && _workspace_config) {
			KConfig * _new_config = _workspace_config->copyTo (workspaceConfigFileName (workspaceURL ()));
			delete _workspace_config;
			_workspace_config = _new_config;
		} else {
			delete _workspace_config;
			_workspace_config = 0;
		}
		emit (workspaceUrlChanged (url));
	}
}

void RKWorkplace::saveSettings () {
	RK_TRACE (APP);

	KConfigGroup toolbar_config = KGlobal::config ()->group ("ToolwindowBars");
	for (int i = 0; i < TOOL_WINDOW_BAR_COUNT; ++i) tool_window_bars[i]->saveSize (toolbar_config);
}

void RKWorkplace::initActions (KActionCollection *ac, const char *left_id, const char *right_id) {
	RK_TRACE (APP);

	wview->initActions (ac, left_id, right_id);
}

void RKWorkplace::attachWindow (RKMDIWindow *window) {
	RK_TRACE (APP);
	RK_ASSERT (windows.contains (window));		// This should not happen for now.

	if (!window->isAttached ()) {
		QWidget *old_parent = window->parentWidget ();
		window->prepareToBeAttached ();
		if (old_parent && qobject_cast<DetachedWindowContainer*> (old_parent)) {
			old_parent->deleteLater ();
		}
	}

	// all the rest is done, even if the window was previously "Attached", as this may also mean it was freshly created
	window->state = RKMDIWindow::Attached;
	if (window->isToolWindow ()) {
		if (!window->tool_window_bar) placeInToolWindowBar (window, RKToolWindowList::Bottom);
		else window->tool_window_bar->reclaimDetached (window);
	} else {
		view ()->addWindow (window);
		view ()->topLevelWidget ()->raise ();
		view ()->topLevelWidget ()->activateWindow ();
	}

	RK_ASSERT (window->getPart ());
	RKWardMainWindow::getMain ()->partManager ()->addPart (window->getPart ());
}

void RKWorkplace::detachWindow (RKMDIWindow *window, bool was_attached) {
	RK_TRACE (APP);
	if (!window) return;
	RK_ASSERT (windows.contains (window));		// Can't detach a window that is not registered

	window->prepareToBeDetached ();
	window->state = RKMDIWindow::Detached;

	RK_ASSERT (window->getPart ());
	if (was_attached) {
		RKWardMainWindow::getMain ()->partManager ()->removePart (window->getPart ());
		if (!window->isToolWindow ()) view ()->removeWindow (window);
	}

	DetachedWindowContainer *detached = new DetachedWindowContainer (window);
	detached->show ();
	if (!was_attached) window->activate ();
}

void RKWorkplace::addWindow (RKMDIWindow *window, bool attached) {
	RK_TRACE (APP);

	// first handle placement overrides
	if (window_placement_override == RKMDIWindow::Attached) {
		if (!attached) window->state = RKMDIWindow::Detached;   // Ok, yeah. BAD style. But windows that would go to detached by default would not prepareToBeAttached(), without this.
		                                                        // TODO: Create third state: NotManaged
		attached = true;
	} else if (window_placement_override == RKMDIWindow::Detached) {
		attached = false;
	}

	// style override. Windows may or may not handle this
	if (!window_style_override.isEmpty ()) window->setWindowStyleHint (window_style_override);

	// next handle name overrides, if any
	if (!window_name_override.isEmpty ()) {
		int pos = -1;
		for (int i = 0; i < named_windows.size (); ++i) {
			if (named_windows[i].id == window_name_override) {
				pos = i;
				break;
			}
		}
		if (pos < 0) {   // not yet known: implicit registration -> create corresponing named_window_spec on the fly.
			registerNamedWindow (window_name_override, 0, attached ? RKWardMainWindow::getMain () : 0);
			pos = named_windows.size () - 1;
		}

		NamedWindow &nw = named_windows[pos];
		if (nw.window != window) {
			if (nw.window) {  // kill existing window (going to be replaced)
				// TODO: this is not really elegant, yet, as it will change tab-placement (for attached windows), and discard / recreate container (for detached windows)
				disconnect (nw.window, SIGNAL (destroyed(QObject*)), this, SLOT (namedWindowDestroyed(QObject*)));
				nw.window->deleteLater ();
			}
			nw.window = window;
			connect (nw.window, SIGNAL (destroyed(QObject*)), this, SLOT (namedWindowDestroyed(QObject*)));
		}
		named_windows[pos] = nw;

		// add window in the correct area
		if (nw.parent == RKWardMainWindow::getMain ()) attached = true;
		else if (nw.parent == 0) attached = false;
		else { // custom parent
			window->prepareToBeAttached ();
			window->setParent (nw.parent);
			// TODO: do this is somewhat inconsistent. But such windows are not attached to the main workplace view, which makes them rather behave detached.
			window->state = RKMDIWindow::Detached;
			// NOTE: The window is _not_ added to the window list/window history in this case.
			return;
		}
	}

	windows.append (window);
	connect (window, SIGNAL (destroyed(QObject*)), this, SLOT (removeWindow(QObject*)));
	connect (window, SIGNAL (windowActivated(RKMDIWindow*)), history, SLOT (windowActivated(RKMDIWindow*)));
	if (window->isToolWindow () && !window->tool_window_bar) return;

	if (attached) attachWindow (window);
	else detachWindow (window, false);
}

void RKWorkplace::placeToolWindows() {
	RK_TRACE (APP);

	foreach (const RKToolWindowList::ToolWindowRepresentation& rep, RKToolWindowList::registeredToolWindows ()) {
		placeInToolWindowBar (rep.window, rep.default_placement);
		getHistory ()->popLastWindow (rep.window);	// windows send a spurious activation signal triggered from KPartsManager::addPart(), so we pop them, again
	}
}

void RKWorkplace::placeInToolWindowBar (RKMDIWindow *window, int position) {
	RK_TRACE (APP);

	RK_ASSERT (window->isToolWindow ());
	bool needs_registration = (!window->tool_window_bar && (position != RKToolWindowList::Nowhere));
	if ((position < 0) || (position >= TOOL_WINDOW_BAR_COUNT)) {
		RK_ASSERT (position == RKToolWindowList::Nowhere);	// should never happen...
		position = RKToolWindowList::Nowhere;		// ... but let's set this explicitly, in case of a broken workplace representation
	}
	if (position == RKToolWindowList::Nowhere) {
		if (window->tool_window_bar) window->tool_window_bar->removeWidget (window);
	} else {
		tool_window_bars[position]->addWidget (window);
	}

	if (!windows.contains (window)) addWindow (window, true);	// first time we see this window
	else if (needs_registration) attachWindow (window);
}

void RKWorkplace::setWindowPlacementOverrides(const QString& placement, const QString& name, const QString& style) {
	RK_TRACE (APP);

	if (placement == "attached") window_placement_override = RKMDIWindow::Attached;
	else if (placement == "detached") window_placement_override = RKMDIWindow::Attached;
	else {
		RK_ASSERT (placement.isEmpty ());
		window_placement_override = RKMDIWindow::AnyWindowState;
	}
	window_name_override = name;
	window_style_override = style;
}

void RKWorkplace::registerNamedWindow (const QString& id, QObject* owner, QWidget* parent, RKMDIWindow* window) {
	RK_TRACE (APP);

	NamedWindow nw;
	nw.id = id;
	nw.owner = owner;
	nw.parent = parent;
	nw.window = window;

	for (int i = 0; i < named_windows.size (); ++i) {
		RK_ASSERT (named_windows[i].id != id);
	}

	named_windows.append (nw);
	if (owner) connect (owner, SIGNAL (destroyed(QObject*)), this, SLOT (namedWindowOwnerDestroyed(QObject*)));
	if (window) connect (window, SIGNAL (destroyed(QObject*)), this, SLOT (namedWindowDestroyed(QObject*)));
}

RKMDIWindow* RKWorkplace::getNamedWindow (const QString& id) {
	RK_TRACE (APP);

	for (int i = 0; i < named_windows.size (); ++i) {
		if (named_windows[i].id == id) {
			return named_windows[i].window;
		}
	}

	return 0;
}

void RKWorkplace::namedWindowDestroyed (QObject* window) {
	RK_TRACE (APP);

	for (int i = 0; i < named_windows.size (); ++i) {
		if (named_windows[i].window == window) {
			if (!named_windows[i].owner) {
				named_windows.removeAt (i);
				return;
			} else {
				named_windows[i].window = 0;
			}
		}
	}
}

void RKWorkplace::namedWindowOwnerDestroyed (QObject* owner) {
	RK_TRACE (APP);

	for (int i = 0; i < named_windows.size (); ++i) {
		if (named_windows[i].owner == owner) {
			if (named_windows[i].window) {
				named_windows[i].window->deleteLater ();
			}
			named_windows.removeAt (i);
			return;
		}
	}
}

bool RKWorkplace::openAnyUrl (const KUrl &url, const QString &known_mimetype, bool force_external) {
	RK_TRACE (APP);

	if (url.protocol () == "rkward") {
		if (RKHTMLWindow::handleRKWardURL (url)) return true;
	}
	KMimeType::Ptr mimetype;
	if (!known_mimetype.isEmpty ()) mimetype = KMimeType::mimeType (known_mimetype);
	else mimetype = KMimeType::findByUrl (url);

	if (!force_external) {
	// NOTE: Currently a known mimetype implies that the URL is local or served from the local machine.
	// Thus, external web pages are *not* opened, here. Which is the behavior we want, although the implementation is ugly
		if (mimetype->is ("text/html")) {
			openHelpWindow (url, true);
			return true;	// TODO
		}
		if (url.fileName ().toLower ().endsWith (".rdata") || url.fileName ().toLower ().endsWith (".rda")) {
			RKWardMainWindow::getMain ()->askOpenWorkspace (url);
			return true;	// TODO
		}
		if (mimetype->is ("text/plain")) {
			return (openScriptEditor (url, QString (), RKSettingsModuleCommandEditor::matchesScriptFileFilter (url.fileName())));
		}
		RK_DEBUG (APP, DL_INFO, "Don't know how to handle mimetype %s.", qPrintable (mimetype->name ()));
	}

	if (KMessageBox::questionYesNo (this, i18n ("The url you are trying to open ('%1') is not a local file or the filetype is not supported by RKWard. Do you want to open the url in the default application?", url.prettyUrl ()), i18n ("Open in default application?")) != KMessageBox::Yes) {
		return false;
	}
	KRun *runner = new KRun (url, topLevelWidget());		// according to KRun-documentation, KRun will self-destruct when done.
	runner->setRunExecutables (false);
	return false;
}

RKMDIWindow* RKWorkplace::openScriptEditor (const KUrl &url, const QString& encoding, bool use_r_highlighting, bool read_only, const QString &force_caption, bool delete_on_close) {
	RK_TRACE (APP);

// is this url already opened?
	if (!url.isEmpty ()) {
	  	RKWorkplaceObjectList script_windows = getObjectList (RKMDIWindow::CommandEditorWindow, RKMDIWindow::AnyWindowState);
		for (RKWorkplaceObjectList::const_iterator it = script_windows.constBegin (); it != script_windows.constEnd (); ++it) {
			  KUrl ourl = static_cast<RKCommandEditorWindow *> (*it)->url ();
			  if (url == ourl) {
				  (*it)->activate ();
				  return (*it);
			  }
		}
	}

	RKCommandEditorWindow *editor = new RKCommandEditorWindow (view (), use_r_highlighting);

	if (!url.isEmpty ()) {
		if (!editor->openURL (url, encoding, use_r_highlighting, read_only, delete_on_close)) {
			delete editor;
			KMessageBox::messageBox (view (), KMessageBox::Error, i18n ("Unable to open \"%1\"", url.prettyUrl ()), i18n ("Could not open command file"));
			return 0;
		}
	}

	if (!force_caption.isEmpty ()) editor->setCaption (force_caption);
	addWindow (editor);
	return (editor);
}

RKMDIWindow* RKWorkplace::openHelpWindow (const KUrl &url, bool only_once) {
	RK_TRACE (APP);

	if (url.isEmpty ()) {
		RK_ASSERT (false);
		return 0;
	}

	if (only_once) {
		RKWorkplaceObjectList help_windows = getObjectList (RKMDIWindow::HelpWindow, RKMDIWindow::AnyWindowState);
		for (RKWorkplaceObjectList::const_iterator it = help_windows.constBegin (); it != help_windows.constEnd (); ++it) {
			if (static_cast<RKHTMLWindow *> (*it)->url ().equals (url, KUrl::CompareWithoutTrailingSlash | KUrl::CompareWithoutFragment)) {
				(*it)->activate ();
				return (*it);
			}
		}
	}

	RKHTMLWindow *hw = new RKHTMLWindow (view (), RKHTMLWindow::HTMLHelpWindow);
	hw->openURL (url);
	addWindow (hw);
	return (hw);
}

RKMDIWindow* RKWorkplace::openOutputWindow (const KUrl &url) {
	RK_TRACE (APP);

	RKHTMLWindow *w = RKOutputWindowManager::self ()->getCurrentOutputWindow ();
	if (!windows.contains (w)) {
		addWindow (w);
	} else {
		w->activate ();
	}
	return (w);
}

void RKWorkplace::newX11Window (WId window_to_embed, int device_number) {
	RK_TRACE (APP);

	RKCaughtX11Window *window = new RKCaughtX11Window (window_to_embed, device_number);
	window->state = RKMDIWindow::Detached;
	addWindow (window, false);
}

void RKWorkplace::newRKWardGraphisWindow (RKGraphicsDevice* dev, int device_number) {
	RK_TRACE (APP);

	RKCaughtX11Window *window = new RKCaughtX11Window (dev, device_number);
	window->state = RKMDIWindow::Detached;
	addWindow (window, false);
}

void RKWorkplace::newObjectViewer (RObject *object) {
	RK_TRACE (APP);
	RK_ASSERT (object);

	RKWorkplaceObjectList object_windows = getObjectList (RKMDIWindow::ObjectWindow, RKMDIWindow::AnyWindowState);
	for (RKWorkplaceObjectList::const_iterator it = object_windows.constBegin (); it != object_windows.constEnd (); ++it) {
		if (static_cast<RObjectViewer *> (*it)->object () == object) {
			(*it)->activate ();
			return;
		}
	}

	RObjectViewer *ov = new RObjectViewer (view (), object);
	addWindow (ov);
}

bool RKWorkplace::canEditObject (RObject *object) {
	RK_TRACE (APP);
	
	if (object->isDataFrame ()) {
		return true;
	} else if (object->isVariable () && object->parentObject ()->isDataFrame ()) {
		return true;
	}
	return false;
}

RKEditor* RKWorkplace::editNewDataFrame (const QString &name) {
	RK_TRACE (APP);

	RKEditorDataFrame* ed = new RKEditorDataFrame (name, 0);
	addWindow (ed);
	ed->activate ();

	return ed;
}

RKEditor *RKWorkplace::editObject (RObject *object) {
	RK_TRACE (APP);
	RK_ASSERT (object);

	RObject *iobj = object;
	RKEditor *ed = 0;
	RKEditor *existing_editor = object->editor ();
	if (!existing_editor) {
		if (!iobj->isDataFrame ()) {
			if (iobj->isVariable () && iobj->parentObject ()->isDataFrame ()) {
				iobj = iobj->parentObject ();
			} else {
				return 0;
			}
		}

		unsigned long size = 1;
		foreach (int dim, iobj->getDimensions ()) {
			size *= dim;
		}
		if ((RKSettingsModuleGeneral::warnLargeObjectThreshold () != 0) && (size > RKSettingsModuleGeneral::warnLargeObjectThreshold ())) {
			if (KMessageBox::warningContinueCancel (view (), i18n ("You are about to edit object \"%1\", which is very large (%2 fields). RKWard is not optimized to handle very large objects in the built in data editor. This will use a lot of memory, and - depending on your system - might be very slow. For large objects it is generally recommended to edit using command line means or to split into smaller chunks before editing. On the other hand, if you have enough memory, or the data is simple enough (numeric data is easier to handle, than factor), editing may not be a problem at all. You can configure this warning (or turn it off entirely) under Settings->Configure RKWard->General.\nReally edit object?", iobj->getFullName (), size), i18n ("About to edit very large object")) != KMessageBox::Continue) {
				return 0;
			}
		}

		ed = new RKEditorDataFrame (static_cast<RContainerObject*> (iobj), 0);
		addWindow (ed);
	} else {
		ed = existing_editor;
	}

	ed->activate ();
	return ed;
}

void RKWorkplace::flushAllData () {
	RK_TRACE (APP);

	for (RKWorkplaceObjectList::const_iterator it = windows.constBegin (); it != windows.constEnd (); ++it) {
		if ((*it)->type == RKMDIWindow::DataEditorWindow) {
			static_cast<RKEditor *> (*it)->flushChanges ();
		}
	}
}

void RKWorkplace::closeWindow (RKMDIWindow *window) {
	RK_TRACE (APP);
	RK_ASSERT (windows.contains (window));

	bool tool_window = window->isToolWindow ();
	window->close (true);		// all the rest should happen in removeWindow ()
	
	if (tool_window) windowRemoved ();	// for regular windows, this happens in removeWindow(), already
}

void RKWorkplace::closeActiveWindow () {
	RK_TRACE (APP);

	RKMDIWindow *w = activeWindow (RKMDIWindow::Attached);
	if (w) closeWindow (w);
}

RKWorkplace::RKWorkplaceObjectList RKWorkplace::getObjectList (int type, int state) {
	RK_TRACE (APP);

	RKWorkplaceObjectList ret;
	for (RKWorkplaceObjectList::const_iterator it = windows.constBegin (); it != windows.constEnd (); ++it) {
		if (((*it)->type & type) && ((*it)->state & state)) {
			ret.append ((*it));
		}
	}
	return ret;
}

void RKWorkplace::closeAll (int type, int state) {
	RK_TRACE (APP);

	RKWardMainWindow::getMain ()->lockGUIRebuild (true);
	RKWorkplaceObjectList list_to_close = getObjectList (type, state);
	for (RKWorkplaceObjectList::const_iterator it = list_to_close.constBegin (); it != list_to_close.constEnd (); ++it) {
		closeWindow (*it);
	}
	RKWardMainWindow::getMain ()->lockGUIRebuild (false);
}

void RKWorkplace::removeWindow (QObject *object) {
	RK_TRACE (APP);
	RKMDIWindow *window = static_cast<RKMDIWindow *> (object);

	// remove from history first (otherwise, we might find it there, when trying to activate a new window)
	history->removeWindow (window);

	// WARNING: the window is dead. Don't call any functions on it.

	RK_ASSERT (windows.contains (window));
	windows.removeAll (window);		// do this first! view()->removeWindow will call activePage() indirectly from setCaption, causing us to iterate over all known windows!
	if (view ()->hasWindow (window)) view ()->removeWindow (window, true);

	windowRemoved ();
}

void RKWorkplace::windowRemoved () {
	RK_TRACE (APP);

	if (activeWindow (RKMDIWindow::AnyWindowState) != 0) return;	// something already active

	// try to activate an attached document window, first
	RKMDIWindow *window = view ()->activePage ();
	if (window) {
		window->activate (true);
		return;
	}

	// some document window in the history? Try that.
	window = history->previousDocumentWindow ();
	if (window) {
		window->activate (true);
		return;
	}

	// now try to activate an attached (tool) window, if one is visible
	for (RKWorkplaceObjectList::const_iterator it = windows.constBegin (); it != windows.constEnd (); ++it) {
		if ((*it)->isAttached ()) {
			if ((*it)->isVisible ()) {
				(*it)->activate (true);
				return;
			}
		}
	}

	// nothing, yet? Try *any* visible window
	for (RKWorkplaceObjectList::const_iterator it = windows.constBegin (); it != windows.constEnd (); ++it) {
		if ((*it)->isVisible ()) {
			(*it)->activate (true);
			return;
		}
	}

	// give up
}

RKMDIWindow *RKWorkplace::activeWindow (RKMDIWindow::State state) {
	RK_TRACE (APP);

	RKMDIWindow *ret = 0;
	for (RKWorkplaceObjectList::const_iterator it = windows.constBegin (); it != windows.constEnd (); ++it) {
		if (!(state & ((*it)->state))) continue;

		if ((*it)->isActive ()) {
			ret = *it;
			break;
		}
	}

	return (ret);
}

QStringList RKWorkplace::makeWorkplaceDescription () {
	RK_TRACE (APP);

	QStringList workplace_description;

	// first, save the base directory of the workplace. This allows us to cope better with moved workspaces while restoring.
	KUrl base_url = workspaceURL ();
	base_url.setPath (base_url.directory ());
	if (base_url.isLocalFile () && base_url.hasPath ()) workplace_description.append ("base::::" + base_url.url ());

	// window order in the workplace view may have changed with respect to our list. Thus we first generate a properly sorted list
	RKWorkplaceObjectList list = getObjectList (RKMDIWindow::DocumentWindow, RKMDIWindow::Detached);
	for (int i=0; i < wview->count (); ++i) {
		list.append (static_cast<RKMDIWindow*> (wview->widget (i)));
	}
	list.append (getObjectList (RKMDIWindow::ToolWindow, RKMDIWindow::AnyWindowState));
	foreach (RKMDIWindow *win, list) {
		QString type, specification;
		QStringList params;
		if (win->isType (RKMDIWindow::DataEditorWindow)) {
			type = "data";
			specification = static_cast<RKEditor*> (win)->getObject ()->getFullName ();
		} else if (win->isType (RKMDIWindow::CommandEditorWindow)) {
			type = "script";
			specification = static_cast<RKCommandEditorWindow*> (win)->url ().url ();
		} else if (win->isType (RKMDIWindow::OutputWindow)) {
			type = "output";
			specification = static_cast<RKHTMLWindow*> (win)->url ().url ();
		} else if (win->isType (RKMDIWindow::HelpWindow)) {
			type = "help";
			specification = static_cast<RKHTMLWindow*> (win)->restorableUrl ().url ();
		} else if (win->isToolWindow ()) {
			type = RKToolWindowList::idOfWindow (win);
		}
		if (!type.isEmpty ()) {
			if (!win->isAttached ()) {
				params.append (QString ("detached,") + QString::number (win->x ()) + ',' + QString::number (win->y ()) + ',' + QString::number (win->width ()) + ',' + QString::number (win->height ()));
			}
			if (win->isToolWindow ()) {
				int sidebar = RKToolWindowList::Nowhere;
				for (int i = 0; i < TOOL_WINDOW_BAR_COUNT; ++i) {
					if (win->tool_window_bar == tool_window_bars[i]) {
						sidebar = i;
						break;
					}
				}
				params.append (QString ("sidebar,") + QString::number (sidebar));
			}
			workplace_description.append (type + "::" + params.join (":") + "::" + specification);
		}
	}
	return workplace_description;
}

void RKWorkplace::saveWorkplace (RCommandChain *chain) {
	RK_TRACE (APP);
// TODO: This is still a mess. All workplace-related settings, including the workspaceConfig(), should be saved to a single place, and in 
// standard KConfig format.
	if (RKSettingsModuleGeneral::workplaceSaveMode () != RKSettingsModuleGeneral::SaveWorkplaceWithWorkspace) return;

	RKGlobals::rInterface ()->issueCommand ("rk.save.workplace(description=" + RObject::rQuote (makeWorkplaceDescription().join ("\n")) + ')', RCommand::App, i18n ("Save Workplace layout"), 0, 0, chain);
}

void RKWorkplace::restoreWorkplace (RCommandChain *chain, bool merge) {
	RK_TRACE (APP);
	if (RKSettingsModuleGeneral::workplaceSaveMode () != RKSettingsModuleGeneral::SaveWorkplaceWithWorkspace) return;

	QString no_close_windows;
	if (merge) no_close_windows = "close.windows = FALSE";
	RKGlobals::rInterface ()->issueCommand ("rk.restore.workplace(" + no_close_windows + ')', RCommand::App, i18n ("Restore Workplace layout"), 0, 0, chain);
}

KUrl checkAdjustRestoredUrl (const QString &_url, const QString old_base) {
	KUrl url (_url);

	if (old_base.isEmpty ()) return (url);
	KUrl new_base_url = RKWorkplace::mainWorkplace ()->workspaceURL ();
	new_base_url.setPath (new_base_url.directory ());
	if (new_base_url.isEmpty ()) return (url);
	KUrl old_base_url (old_base);
	if (old_base_url == new_base_url) return (url);

	// TODO: Should we also care about non-local files? In theory: yes, but stat'ing remote files for existence can take a long time.
	if (!(old_base_url.isLocalFile () && new_base_url.isLocalFile () && url.isLocalFile ())) return (url);

	// if the file exists, unadjusted, return it.
	if (QFileInfo (url.toLocalFile ()).exists ()) return (url);

	// check whether a file exists for the adjusted url
	KUrl relative = KUrl::fromLocalFile (new_base_url.path () + '/' + KUrl::relativePath (old_base_url.path (), url.path ()));
	relative.cleanPath ();
// 	if (QFileInfo (relative.toLocalFile ()).exists ()) return (relative);
	return (url);
}

void RKWorkplace::restoreWorkplace (const QStringList &description) {
	RK_TRACE (APP);

	RKWardMainWindow::getMain ()->lockGUIRebuild (true);
	QString base;
	for (int i = 0; i < description.size (); ++i) {
		// Item format for rkward <= 0.5.4: "type:specification"
		// Item format for rkward <= 0.5.5: "type::[optional_params1[:optional_params2[:...]]]::specification"
		int typeend = description[i].indexOf (':');
		if ((typeend < 0) || (typeend >= (description[i].size () - 1))) {
			RK_ASSERT (false);
			continue;
		}
		QString type, specification;
		QStringList params;
		type = description[i].left (typeend);
		if (description[i].at (typeend + 1) == ':') {	// rkward 0.5.5 or later
			int specstart = description[i].indexOf ("::", typeend + 2);
			if (specstart < typeend) {
				RK_ASSERT (false);
				continue;
			}
			params = description[i].mid (typeend + 2, specstart - typeend - 2).split (':', QString::SkipEmptyParts);
			specification = description[i].mid (specstart + 2);
		} else {
			specification = description[i].mid (typeend + 1);
		}

		RKMDIWindow *win = 0;
		if (type == "base") {
			RK_ASSERT (i == 0);
			base = specification;
		} else if (type == "data") {
			RObject *object = RObjectList::getObjectList ()->findObject (specification);
			if (object) win = editObject (object);
		} else if (type == "script") {
			win = openScriptEditor (checkAdjustRestoredUrl (specification, base));
		} else if (type == "output") {
			win = openOutputWindow (checkAdjustRestoredUrl (specification, base));
		} else if (type == "help") {
			win = openHelpWindow (checkAdjustRestoredUrl (specification, base), true);
		} else {
			win = RKToolWindowList::findToolWindowById (type);
			RK_ASSERT (win);
		}

		// apply generic window parameters
		if (win) {
			for (int p = 0; p < params.size (); ++p) {
				if (params[p].startsWith ("sidebar")) {
					int position = params[p].section (',', 1).toInt ();
					placeInToolWindowBar (win, position);
				}
				if (params[p].startsWith ("detached")) {
					QStringList geom = params[p].split (',');
					win->hide ();
					win->setGeometry (geom.value (1).toInt (), geom.value (2).toInt (), geom.value (3).toInt (), geom.value (4).toInt ());
					detachWindow (win);
				}
			}
		}
	}
	RKWardMainWindow::getMain ()->lockGUIRebuild (false);
}

///////////////////////// END RKWorkplace ////////////////////////////
///////////////////// BEGIN RKMDIWindowHistory ///////////////////////

#include "../misc/rkstandardicons.h"
#include <QListWidget>

class RKMDIWindowHistoryWidget : public QListWidget {
public:
	RKMDIWindowHistoryWidget () : QListWidget (0) {
		RK_TRACE (APP);

		current = 0;
		setFocusPolicy (Qt::StrongFocus);
		setWindowFlags (Qt::Popup);
	}

	~RKMDIWindowHistoryWidget () {
		RK_TRACE (APP);
	}

	void update (const QList<RKMDIWindow*> windows) {
		RK_TRACE (APP);

		clear ();
		_windows = windows;
		for (int i = windows.count () - 1; i >= 0; --i) {		// most recent top
			RKMDIWindow *win = windows[i];
			QListWidgetItem *item = new QListWidgetItem (this);
			item->setIcon (RKStandardIcons::iconForWindow (win));
			item->setText (win->windowTitle ());
		}
		if (current >= count ()) current = count () - 1;
		if (current < 0) {
			hide ();
			return;
		}
		setCurrentRow (current);
	}

	void next () {
		RK_TRACE (APP);

		if (--current < 0) current = count () - 1;
		setCurrentRow (current);
	}

	void prev () {
		RK_TRACE (APP);

		if (++current >= count ()) current = 0;
		setCurrentRow (current);
	}

private:
	void focusOutEvent (QFocusEvent *) {
		RK_TRACE (APP);

		deleteLater ();
	}

	void keyReleaseEvent (QKeyEvent *ev) {
		RK_TRACE (APP);

		if (ev->modifiers () == Qt::NoModifier) {
			commit ();
		}
	}

	void mouseReleaseEvent (QMouseEvent *ev) {
		RK_TRACE (APP);

		// HACK to get by without slots, and the associated moc'ing
		QListWidget::mouseReleaseEvent (ev);
		commit ();
	}

	void commit () {
		RK_TRACE (APP);

		current = currentRow ();
		if ((current > 0) && (current < count ())) {
			RKMDIWindow *win = _windows.value (count () - 1 - current);
			RK_ASSERT (win);
			win->activate (true);
		}
		deleteLater ();
	}

	int current;
	QList<RKMDIWindow*> _windows;
};

RKMDIWindowHistory::RKMDIWindowHistory (QObject *parent) : QObject (parent) {
	RK_TRACE (APP);

	switcher = 0;
}

RKMDIWindowHistory::~RKMDIWindowHistory () {
	RK_TRACE (APP);

	RK_DEBUG (APP, DL_DEBUG, "Remaining windows in history: %d", recent_windows.count ());
}

void RKMDIWindowHistory::windowActivated (RKMDIWindow *window) {
	RK_TRACE (APP);

	if (!window) return;
	if (!recent_windows.isEmpty () && (window == recent_windows.last ())) return;

	// update lists
	recent_windows.removeAll (window);		// remove dupes
	recent_windows.append (window);

	updateSwitcher ();
}

void RKMDIWindowHistory::next (KAction* prev_action, KAction *next_action) {
	RK_TRACE (APP);

	if (recent_windows.isEmpty ()) return;
	getSwitcher (prev_action, next_action)->next ();
}

void RKMDIWindowHistory::prev (KAction* prev_action, KAction *next_action) {
	RK_TRACE (APP);

	if (recent_windows.isEmpty ()) return;
	getSwitcher (prev_action, next_action)->prev ();
}

RKMDIWindow* RKMDIWindowHistory::previousDocumentWindow () {
	RK_TRACE (APP);

	for (int i = recent_windows.count () - 1; i >= 0; --i) {
		if (!recent_windows[i]->isToolWindow ()) return (recent_windows[i]);
	}
	return 0;
}

void RKMDIWindowHistory::updateSwitcher () {
	RK_TRACE (APP);

	if (switcher) switcher->update (recent_windows);
}

void RKMDIWindowHistory::removeWindow (RKMDIWindow *window) {
	RK_TRACE (APP);

	recent_windows.removeAll (window);
	updateSwitcher ();
}

RKMDIWindowHistoryWidget* RKMDIWindowHistory::getSwitcher (KAction* prev_action, KAction *next_action) {
	RK_TRACE (APP);

	if (switcher) return switcher;

	switcher = new RKMDIWindowHistoryWidget ();
	connect (switcher, SIGNAL (destroyed(QObject*)), this, SLOT (switcherDestroyed()));
	switcher->addAction (prev_action);
	switcher->addAction (next_action);
	switcher->update (recent_windows);
	switcher->show ();
	QWidget *act = QApplication::activeWindow ();
	if (act) {
		int center_x = act->x () + act->width () / 2;
		int center_y = act->y () + act->height () / 2;
		switcher->move (center_x - switcher->width () / 2, center_y - switcher->height () / 2);
	} else {
		RK_ASSERT (false);
	}
	switcher->setFocus ();

	return switcher;
}

void RKMDIWindowHistory::switcherDestroyed () {
	RK_TRACE (APP);

	RK_ASSERT (switcher);
	switcher = 0;
}

void RKMDIWindowHistory::popLastWindow (RKMDIWindow* match) {
	RK_TRACE (APP);

	if (recent_windows.isEmpty ()) return;
	else if (recent_windows.last () == match) recent_windows.removeLast ();
	updateSwitcher ();
}

#include "rkworkplace.moc"