summaryrefslogtreecommitdiffstats
path: root/dozentenmodul/src/main/java/org/openslx/dozmod/gui/window/LectureListWindow.java
blob: e45fcac846ca35b1eb02407b660841d2157ad10b (plain) (blame)
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
package org.openslx.dozmod.gui.window;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import org.apache.log4j.Logger;
import org.apache.thrift.TException;
import org.openslx.bwlp.thrift.iface.ImageDetailsRead;
import org.openslx.bwlp.thrift.iface.ImageVersionDetails;
import org.openslx.bwlp.thrift.iface.LectureSummary;
import org.openslx.bwlp.thrift.iface.UserInfo;
import org.openslx.dozmod.gui.Gui;
import org.openslx.dozmod.gui.MainWindow;
import org.openslx.dozmod.gui.control.table.ListTable.ListModel;
import org.openslx.dozmod.gui.helper.I18n;
import org.openslx.dozmod.gui.helper.MessageType;
import org.openslx.dozmod.gui.helper.PopupMenu;
import org.openslx.dozmod.gui.helper.TextChangeListener;
import org.openslx.dozmod.gui.window.LectureDetailsWindow.LectureUpdatedCallback;
import org.openslx.dozmod.gui.window.layout.LectureListWindowLayout;
import org.openslx.dozmod.gui.wizard.LectureWizard;
import org.openslx.dozmod.permissions.LecturePerms;
import org.openslx.dozmod.thrift.ImageLocalDetailsActions;
import org.openslx.dozmod.thrift.Session;
import org.openslx.dozmod.thrift.ThriftActions;
import org.openslx.dozmod.thrift.ThriftActions.DeleteLectureCallback;
import org.openslx.dozmod.thrift.cache.LectureCache;
import org.openslx.dozmod.thrift.cache.UserCache;
import org.openslx.util.QuickTimer;
import org.openslx.util.QuickTimer.Task;
import org.openslx.util.Util;

/**
 * Window for displaying a table with the available lectures.
 * Lectures can be created and deleted here.
 */
public class LectureListWindow extends LectureListWindowLayout {

	/**
	 * Version for serialization.
	 */
	private static final long serialVersionUID = 3135935034893934652L;

	private final static Logger LOGGER = Logger.getLogger(LectureListWindow.class);

	public final LectureListWindow me = this;

	// Filter types as an enum
	public enum FilterType {
		ALL(I18n.WINDOW.getString("LectureList.FilterType.all"), null),
		OWN(I18n.WINDOW.getString("LectureList.FilterType.own"), new RowFilter<ListModel<LectureSummary>, Integer>() {
			public boolean include(Entry<? extends ListModel<LectureSummary>, ? extends Integer> entry) {
				LectureSummary lecture = entry.getModel().getModelRow(entry.getIdentifier());
				return lecture.userPermissions.admin || lecture.ownerId.equals(Session.getUserId());
			}
		}),
		ACTIVE(I18n.WINDOW.getString("LectureList.FilterType.active"), new RowFilter<ListModel<LectureSummary>, Integer>() {
			public boolean include(Entry<? extends ListModel<LectureSummary>, ? extends Integer> entry) {
				LectureSummary lecture = entry.getModel().getModelRow(entry.getIdentifier());
				return lecture.isEnabled && lecture.endTime > Util.unixTime();
			}
		}),
		EDITABLE(I18n.WINDOW.getString("LectureList.FilterType.editable"), new RowFilter<ListModel<LectureSummary>, Integer>() {
			public boolean include(Entry<? extends ListModel<LectureSummary>, ? extends Integer> entry) {
				LectureSummary lecture = entry.getModel().getModelRow(entry.getIdentifier());
				return LecturePerms.canEdit(lecture);
			}
		}),
		EXPIRING(I18n.WINDOW.getString("LectureList.FilterType.expiring"), new RowFilter<ListModel<LectureSummary>, Integer>() {
			public boolean include(Entry<? extends ListModel<LectureSummary>, ? extends Integer> entry) {
				LectureSummary lecture = entry.getModel().getModelRow(entry.getIdentifier());
				return Math.abs(lecture.endTime - Util.unixTime()) < 86400 * 7;
			}
		}),
		EXAMS(I18n.WINDOW.getString("LectureList.FilterType.exams"), new RowFilter<ListModel<LectureSummary>, Integer>() {
			public boolean include(Entry<? extends ListModel<LectureSummary>, ? extends Integer> entry) {
				LectureSummary lecture = entry.getModel().getModelRow(entry.getIdentifier());
				return lecture.isExam;
			}
		});

		private final String name;
		
		private final RowFilter<ListModel<LectureSummary>, Integer> filter;

		private FilterType(String name, RowFilter<ListModel<LectureSummary>, Integer> filter) {
			this.name = name;
			this.filter = filter;
		}

		@Override
		public String toString() {
			return name;
		}
	}

	private Pattern searchFieldPattern = null;

	private final RowFilter<ListModel<LectureSummary>, Integer> filterSearchTerm = new RowFilter<ListModel<LectureSummary>, Integer>() {
		public boolean include(Entry<? extends ListModel<LectureSummary>, ? extends Integer> entry) {
			LectureSummary lecture = tblLectures.getModelRow(entry.getIdentifier());
			if (searchFieldPattern.matcher(lecture.lectureName).find())
				return true;
			if (chkSearchInDescription.isSelected()) {
				String description = lecture.description;
				if (description != null) {
					if (searchFieldPattern.matcher(description).find())
						return true;
				} else {
					LOGGER.debug("Description is null: cannot be searched in description");
				}
			}
			UserInfo user = UserCache.find(lecture.ownerId);
			if (user == null)
				return false;
			if (searchFieldPattern.matcher(user.firstName).find())
				return true;
			if (searchFieldPattern.matcher(user.lastName).find())
				return true;
			if (searchFieldPattern.matcher(user.eMail).find())
				return true;
			return false;
		}
	};

	/**
	 * Popup menu items
	 */
	private JMenuItem popupItemNew = new JMenuItem(I18n.WINDOW.getString("LectureList.MenuItem.new.text"));
	private JMenuItem popupItemEdit = new JMenuItem(I18n.WINDOW.getString("LectureList.MenuItem.edit.text"));
	private JMenuItem popupItemLinked = new JMenuItem(I18n.WINDOW.getString("LectureList.MenuItem.linked.text"));
	private JMenuItem popupItemDownload = new JMenuItem(I18n.WINDOW.getString("LectureList.MenuItem.download.text"));
	private JMenuItem popupItemDelete = new JMenuItem(I18n.WINDOW.getString("LectureList.MenuItem.delete.text"));

	public LectureListWindow() {
		super();

		tblLectures.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

		// filter the objects in the table depending on the search field
		txtSearch.getDocument().addDocumentListener(new TextChangeListener() {
			@Override
			public void changed() {
				String str = txtSearch.getText();
				if (str == null || str.isEmpty()) {
					searchFieldPattern = null;
				} else {
					try {
						searchFieldPattern = Pattern.compile(str, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
						txtSearch.setForeground(UIManager.getColor("TextField.foreground"));
					} catch (PatternSyntaxException ex) {
						txtSearch.setForeground(Color.RED);
					}
				}
				applyFilterOnTable();
			}
		});

		cboFilter.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				txtSearch.setEnabled(true);
				applyFilterOnTable();
			}
		});

		chkSearchInDescription.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				applyFilterOnTable();
			}
		});

		btnNewLecture.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				new LectureWizard(SwingUtilities.getWindowAncestor(me), null, null).setVisible(true);
			}
		});

		btnEditLecture.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				openLectureDetails(tblLectures.getSelectedItem());
			}
		});

		// delete lecture
		btnDeleteLecture.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				deleteLectures(tblLectures.getSelectedItems());
			}
		});

		// return to mainMenu
		btnSwitchView.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				MainWindow.showPage(ImageListWindow.class);
			}
		});

		/**
		 * Popup menu for the version table on the right side
		 */
		final PopupMenu pop = new PopupMenu(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				LectureSummary lecture = tblLectures.getSelectedItem();
				if (lecture == null)
					return;
				if (e.getSource().equals(popupItemNew)) {
					if (Gui.showMessageBox(me, I18n.WINDOW.getString("LectureList.Message.yesNo.switchView"),
							MessageType.QUESTION_YESNO, LOGGER, null)) {
						MainWindow.showPage(ImageListWindow.class);
					}
				}
				if (e.getSource().equals(popupItemEdit)) {
					openLectureDetails(lecture);
				}
				if (e.getSource().equals(popupItemDownload)) {

					//TODO fix for students, who cannot see imageDetails somehow get filesize from server.
					ImageDetailsRead image = ThriftActions.getImageDetails(
							JOptionPane.getFrameForComponent(me), lecture.imageBaseId);
					if (image != null) {
						long versionSize = -1;
						for (ImageVersionDetails version : image.getVersions()) {
							if (version.versionId.equals(lecture.imageVersionId)) {
								versionSize = version.fileSize;
								break;
							}
						}
						if (versionSize != -1) {
							ThriftActions.initDownload(JOptionPane.getFrameForComponent(me),
									lecture.imageVersionId, image.imageName, image.virtId, image.osId,
									versionSize, null);
						}
					}

				}
				if (e.getSource().equals(popupItemLinked)) {
					ImageDetailsWindow.open(JOptionPane.getFrameForComponent(me), lecture.imageBaseId, null, new ImageLocalDetailsActions(JOptionPane.getFrameForComponent(me)));
				}
				if (e.getSource().equals(popupItemDelete)) {
					deleteLectures(tblLectures.getSelectedItems());
				}
			}
		});
		pop.addMenuItem(popupItemNew);
		pop.addMenuItem(popupItemEdit);
		pop.addMenuItem(popupItemLinked);
		pop.addMenuItem(popupItemDownload);
		pop.addSeparator();
		pop.addMenuItem(popupItemDelete);

		// finally the table listeners
		tblLectures.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) {
					if (!Session.canListImages()) {
						Gui.showMessageBox(I18n.WINDOW.getString("LectureList.Message.error.canNotListImages"),
								MessageType.ERROR, LOGGER, null);
						return;
					}
					openLectureDetails(tblLectures.getSelectedItem());
				}
				processClick(e);
			}

			@Override
			public void mousePressed(MouseEvent e) {
				processClick(e);
			}

			@Override
			public void mouseReleased(MouseEvent e) {
				processClick(e);
			}

			private void processClick(MouseEvent e) {

				// rowIndex at mouse cursor
				int mouseRowIndex = tblLectures.rowAtPoint(e.getPoint());

				// is the click event on an already selected row?
				boolean alreadySelectedRow = false;
				for (int i : tblLectures.getSelectedRows()) {
					if (i == mouseRowIndex) {
						alreadySelectedRow = true;
						break;
					}
				}

				if (mouseRowIndex >= 0 && mouseRowIndex < tblLectures.getRowCount()
						&& SwingUtilities.isRightMouseButton(e)) {
					// select row if it wasn't in selection before
					if (!alreadySelectedRow) {
						tblLectures.setRowSelectionInterval(mouseRowIndex, mouseRowIndex);
					}
					if (e.isPopupTrigger()) {
						pop.show(e.getComponent(), e.getX(), e.getY());
					}
				}
			}
		});

		tblLectures.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_F5) {
					refreshList(true);
				}
			}
		});

		tblLectures.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
			@Override
			public void valueChanged(ListSelectionEvent e) {
				LectureSummary item = tblLectures.getSelectedItem();
				updateAvailableOptions(item);
			}
		});
		if (Session.canListImages()) {
			cboFilter.setSelectedItem(FilterType.OWN);
		} else {
			cboFilter.setSelectedItem(FilterType.ALL);
		}
		updateAvailableOptions(null);

		// Some keyboard shortcuts
		tblLectures.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
				KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "details");
		tblLectures.getActionMap().put("details", new AbstractAction() {
			/**
			 * Version for serialization.
			 */
			private static final long serialVersionUID = -5308046358988793018L;

			@Override
			public void actionPerformed(ActionEvent ae) {
				btnEditLecture.doClick();
			}
		});
		tblLectures.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
				KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "delete");
		tblLectures.getActionMap().put("delete", new AbstractAction() {
			/**
			 * Version for serialization.
			 */
			private static final long serialVersionUID = 7494603320083796245L;

			@Override
			public void actionPerformed(ActionEvent ae) {
				btnDeleteLecture.doClick();
			}
		});
	}

	/**
	 * Updates the buttons/popup menu items according to the user's permissions,
	 * status and number of selections
	 * 
	 * @param lecture the lecture to check the user's permissions for, can be
	 *            null
	 */
	private void updateAvailableOptions(LectureSummary lecture) {
		boolean admin = LecturePerms.canAdmin(lecture);
		boolean singleSelection = !(tblLectures.getSelectedRows().length > 1);
		btnEditLecture.setEnabled(Session.canListImages() && singleSelection);
		btnDeleteLecture.setEnabled(admin || !singleSelection);
		popupItemDelete.setEnabled(admin || !singleSelection);
		popupItemDelete.setVisible(admin || !singleSelection);
		popupItemLinked.setEnabled(Session.canListImages());
		popupItemLinked.setVisible(Session.canListImages());
		popupItemDownload.setEnabled(singleSelection);
		popupItemNew.setEnabled(Session.canListImages());
		popupItemNew.setVisible(Session.canListImages());
		popupItemEdit.setEnabled(Session.canListImages() && singleSelection);
		popupItemEdit.setVisible(Session.canListImages() && singleSelection);
	}

	/**
	 * Opens the given lecture's details as a popup window
	 */
	private void openLectureDetails(final LectureSummary lecture) {
		if (lecture == null)
			return;
		LectureDetailsWindow.open((JFrame) SwingUtilities.getWindowAncestor(me), lecture.getLectureId(),
				new LectureUpdatedCallback() {
					@Override
					public void updated(boolean success) {
						refreshList(success);
					}
				});
	}

	/**
	 * Delete a list of lectures and display the lectures, which couldn't be
	 * deleted.
	 * 
	 * @param lectureList the lectures to be deleted.
	 */
	private void deleteLectures(List<LectureSummary> lectureList) {

		ThriftActions.deleteLecture(JOptionPane.getFrameForComponent(me), lectureList,
				new DeleteLectureCallback() {
					@Override
					public void deleted(Map<LectureSummary, TException> fLectures) {
						refreshList(true);
						if (fLectures.size() > 0) {
							StringBuilder builder = new StringBuilder();
							for (LectureSummary lecture : fLectures.keySet()) {
								builder.append("\n\n");
								builder.append(lecture.lectureName + " \n" );
								builder.append(I18n.WINDOW.getString("LectureList.Message.error.deleteLecture",
										fLectures.get(lecture).getLocalizedMessage()));
								LOGGER.error("Couldn't delete lecture " + lecture.lectureName + ", reason:", fLectures.get(lecture) );
								// TODO Should the exception be printed in the debugger or is this to much information?
							}
							Gui.showMessageBox(I18n.WINDOW.getString("LectureList.Message.info.deleteLectures",
									builder.toString()), MessageType.INFO, LOGGER, null);
						}
					}
				});
	}

	/**
	 * Applies the filter entered in the search field to the table
	 */
	private void applyFilterOnTable() {
		if (cboFilter.getSelectedIndex() == -1)
			return;

		// Filter list we are about to fill
		List<RowFilter<ListModel<LectureSummary>, Integer>> filters = new ArrayList<>();

		// string for text in filter text field
		if (searchFieldPattern != null) {
			filters.add(filterSearchTerm);
		}

		// filters from the combobox
		FilterType filterType = (FilterType) cboFilter.getSelectedItem();
		tblLectures.setHighlightOwn(true);
		if (filterType != null && filterType.filter != null) {
			filters.add(filterType.filter);
		}

		// for using multiple filters
		RowFilter<ListModel<LectureSummary>, Integer> andFilters = RowFilter.andFilter(filters);
		tblLectures.getRowSorter().setRowFilter(andFilters);
		setLectureCountLabel(tblLectures.getRowCount());
	}

	private void refreshList(final boolean force) {
		QuickTimer.scheduleOnce(new Task() {
			@Override
			public void fire() {
				final List<LectureSummary> lectureList = LectureCache.get(force);
				Gui.asyncExec(new Runnable() {
					@Override
					public void run() {
						tblLectures.setData(lectureList, true);
						setLectureCountLabel(tblLectures.getRowCount());
					}
				});
			}
		});
	}

	@Override
	public boolean requestHide() {
		if (cboFilter.getSelectedIndex() == -1) {
			cboFilter.setSelectedIndex(0);
		}
		return true;
	}

	@Override
	public void requestShow() {
		// en-/disable buttons when student
		btnSwitchView.setEnabled(Session.canListImages());
		btnNewLecture.setEnabled(Session.canListImages());
		updateAvailableOptions(null);
		refreshList(false);

		if (!Session.canListImages()) 
		{
			disableUnnecessaryButtonsForStudents();
		}
	}

	/**
	 * This funtion disables all unnecessary buttons
	 * when Student is logged in. 
	 */
	public void disableUnnecessaryButtonsForStudents() 
	{
		btnDeleteLecture.setVisible(false);
		btnEditLecture.setVisible(false);
		btnNewLecture.setVisible(false);
		btnSwitchView.setVisible(false);

		btnDeleteLecture.setEnabled(false);
		btnEditLecture.setEnabled(false);
		btnNewLecture.setEnabled(false);
		btnSwitchView.setEnabled(false);

		cboFilter.setVisible(false);
		cboFilter.setEnabled(false);
	}

	public void filterByImageBaseId(final String imageBaseId) {
		if (imageBaseId == null)
			return;
		RowFilter<ListModel<LectureSummary>, Integer> imageFilter = new RowFilter<ListModel<LectureSummary>, Integer>() {
			public boolean include(Entry<? extends ListModel<LectureSummary>, ? extends Integer> entry) {
				LectureSummary lecture = tblLectures.getModelRow(entry.getIdentifier());
				return imageBaseId.equals(lecture.imageBaseId);
			}
		};
		cboFilter.setSelectedIndex(-1);
		txtSearch.setText("");
		txtSearch.setEnabled(false);
		tblLectures.getRowSorter().setRowFilter(imageFilter);
		setLectureCountLabel(tblLectures.getRowCount());
	}
}