Skip to main content
summaryrefslogtreecommitdiffstats
blob: 6146e1326e6ed5af37b70e30249a4cf55fd5951a (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
/*******************************************************************************
 * Copyright (c) 2004, 2008 Tasktop Technologies and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Tasktop Technologies - initial API and implementation
 *     Jevgeni Holodkov - improvements
 *******************************************************************************/

package org.eclipse.mylyn.internal.tasks.ui.views;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerDropAdapter;
import org.eclipse.mylyn.commons.core.StatusHandler;
import org.eclipse.mylyn.internal.provisional.commons.ui.AbstractRetrieveTitleFromUrlJob;
import org.eclipse.mylyn.internal.tasks.core.AbstractTask;
import org.eclipse.mylyn.internal.tasks.core.AbstractTaskCategory;
import org.eclipse.mylyn.internal.tasks.core.LocalTask;
import org.eclipse.mylyn.internal.tasks.core.RepositoryQuery;
import org.eclipse.mylyn.internal.tasks.core.ScheduledTaskContainer;
import org.eclipse.mylyn.internal.tasks.core.TaskCategory;
import org.eclipse.mylyn.internal.tasks.core.UncategorizedTaskContainer;
import org.eclipse.mylyn.internal.tasks.core.UnmatchedTaskContainer;
import org.eclipse.mylyn.internal.tasks.ui.ITasksUiPreferenceConstants;
import org.eclipse.mylyn.internal.tasks.ui.TaskTransfer;
import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin;
import org.eclipse.mylyn.internal.tasks.ui.actions.QueryImportAction;
import org.eclipse.mylyn.internal.tasks.ui.util.TasksUiInternal;
import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector;
import org.eclipse.mylyn.tasks.core.ITask;
import org.eclipse.mylyn.tasks.core.ITaskContainer;
import org.eclipse.mylyn.tasks.core.TaskRepository;
import org.eclipse.mylyn.tasks.ui.TasksUi;
import org.eclipse.mylyn.tasks.ui.TasksUiUtil;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.TransferData;
import org.eclipse.ui.PlatformUI;

/**
 * @author Mik Kersten
 * @author Rob Elves (added URL based task creation support)
 * @author Jevgeni Holodkov
 */
// TODO 3.1 rename to TaskListDropTargetListener
public class TaskListDropAdapter extends ViewerDropAdapter {

	private AbstractTask newTask = null;

	private TransferData currentTransfer;

	public TaskListDropAdapter(Viewer viewer) {
		super(viewer);
		setFeedbackEnabled(true);
	}

	@Override
	public void dragOver(DropTargetEvent event) {
		// support dragging from sources only supporting DROP_LINK
		if (event.detail == DND.DROP_NONE && (event.operations & DND.DROP_LINK) == DND.DROP_LINK) {
			event.detail = DND.DROP_LINK;
		}
		super.dragOver(event);
	}

	@Override
	public boolean performDrop(final Object data) {
		if (data == null) {
			return false;
		}

		Object currentTarget = getCurrentTarget();
		List<ITask> tasksToMove = new ArrayList<ITask>();
		if (isUrl(data) && createTaskFromUrl(data)) {
			tasksToMove.add(newTask);
		} else if (TaskTransfer.getInstance().isSupportedType(currentTransfer) && data instanceof ITask[]) {
			ITask[] tasks = (ITask[]) data;
			for (ITask task : tasks) {
				if (task != null) {
					tasksToMove.add(task);
				}
			}
		} else if (data instanceof String && createTaskFromString((String) data)) {
			tasksToMove.add(newTask);
		} else if (FileTransfer.getInstance().isSupportedType(currentTransfer)) {
			// transfer the context if the target is a Task
//					if (getCurrentTarget() instanceof ITask) {
//						final AbstractTask targetTask = (AbstractTask) getCurrentTarget();
//						final String[] names = (String[]) data;
//						PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
//
//							public void run() {
//								boolean confirmed = MessageDialog.openConfirm(getViewer().getControl().getShell(),
//										"Task Import", "Overwrite the context of the target task with the source's?");
//								if (confirmed) {
//									String path = names[0];
//									File file = new File(path);
//									boolean succeeded = ContextCore.getContextStore().copyContext(file,
//											targetTask.getHandleIdentifier());
//									if (succeeded) {
//										new TaskActivateAction().run(targetTask);
//									}
//								}
//							}
//						});
//					} else {
			// otherwise it is queries or tasks
			final String[] names = (String[]) data;
			for (String path : names) {
				final File file = new File(path);
				final List<RepositoryQuery> queries = new ArrayList<RepositoryQuery>();
				final Set<TaskRepository> repositories = new HashSet<TaskRepository>();
				final List<AbstractTask> readTasks = TasksUiPlugin.getTaskListManager().getTaskListWriter().readTasks(
						file);
				if (file.isFile()) {
					List<RepositoryQuery> readQueries;
					try {
						readQueries = TasksUiPlugin.getTaskListManager().getTaskListWriter().readQueries(file);
						if (readQueries.size() > 0) {
							queries.addAll(readQueries);
							repositories.addAll(TasksUiPlugin.getTaskListManager()
									.getTaskListWriter()
									.readRepositories(file));
						} else {
							repositories.addAll(TasksUiPlugin.getTaskListManager()
									.getTaskListWriter()
									.readRepositories(file));
						}
					} catch (IOException e) {
						StatusHandler.log(new Status(IStatus.WARNING, TasksUiPlugin.ID_PLUGIN, "The specified file \""
								+ file.getName()
								+ "\" is not an exported query. Please, check that you have provided the correct file."));
//						PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
//							public void run() {
//								MessageDialog.openError(null, "Query Import Error",
//										"The specified file is not an exported query. Please, check that you have provided the correct file.");
//							}
//						});
					}
				}

				// FIXME: remove async exec
				PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
					public void run() {
						// TODO: we should consider batching this up
						if (queries.size() > 0) {
							new QueryImportAction().importQueries(queries, repositories, getViewer().getControl()
									.getShell());
						} else {
							TasksUiInternal.importTasks(readTasks, repositories, file, getViewer().getControl()
									.getShell());
						}
					}
				});
			}
		}

		if (currentTarget instanceof LocalTask
				&& areAllLocalTasks(tasksToMove)
				&& getCurrentLocation() == LOCATION_ON
				&& TasksUiPlugin.getDefault().getPreferenceStore().getBoolean(
						ITasksUiPreferenceConstants.LOCAL_SUB_TASKS_ENABLED)) {
			for (ITask task : tasksToMove) {
				if (!((AbstractTask) task).contains(((LocalTask) currentTarget).getHandleIdentifier())) {
					TasksUiInternal.getTaskList().addTask(task, (LocalTask) currentTarget);
				}
			}
		} else {
			for (ITask task : tasksToMove) {
				if (currentTarget instanceof UncategorizedTaskContainer) {
					TasksUiInternal.getTaskList().addTask(task, (UncategorizedTaskContainer) currentTarget);
				} else if (currentTarget instanceof TaskCategory) {
					TasksUiInternal.getTaskList().addTask(task, (TaskCategory) currentTarget);
				} else if (currentTarget instanceof UnmatchedTaskContainer) {
					if (((UnmatchedTaskContainer) currentTarget).getRepositoryUrl().equals(task.getRepositoryUrl())) {
						TasksUiInternal.getTaskList().addTask(task, (AbstractTaskCategory) currentTarget);
					}
				} else if (currentTarget instanceof ITask) {
					ITask targetTask = (ITask) currentTarget;
					AbstractTaskCategory targetCategory = null;
					// TODO: TaskCategory only used what about AbstractTaskCategory descendants?
					ITaskContainer container = TaskCategory.getParentTaskCategory(targetTask);
					if (container instanceof TaskCategory || container instanceof UncategorizedTaskContainer) {
						targetCategory = (AbstractTaskCategory) container;
					} else if (container instanceof UnmatchedTaskContainer) {
						if (((UnmatchedTaskContainer) container).getRepositoryUrl().equals(task.getRepositoryUrl())) {
							targetCategory = (AbstractTaskCategory) container;
						}
					}
					if (targetCategory != null) {
						TasksUiInternal.getTaskList().addTask(task, targetCategory);
					}
				} else if (currentTarget instanceof ScheduledTaskContainer) {
					ScheduledTaskContainer container = (ScheduledTaskContainer) currentTarget;
					TasksUiPlugin.getTaskActivityManager().setScheduledFor((AbstractTask) task,
							container.getDateRange());
				} else if (currentTarget == null) {
					TasksUiInternal.getTaskList().addTask(newTask, TasksUiPlugin.getTaskList().getDefaultCategory());
				}
			}
		}

		// Make new task the current selection in the view
		if (newTask != null) {
			StructuredSelection ss = new StructuredSelection(newTask);
			getViewer().setSelection(ss);
			//getViewer().refresh();
		}

		return true;

	}

	private boolean areAllLocalTasks(List<ITask> tasksToMove) {
		for (ITask task : tasksToMove) {
			if (!(task instanceof LocalTask)) {
				return false;
			}
		}
		return true;
	}

	/**
	 * @return true if string is a http(s) url
	 */
	public boolean isUrl(Object data) {
		String uri = "";
		if (data instanceof String) {
			uri = (String) data;
			if ((uri.startsWith("http://") || uri.startsWith("https://"))) {
				return true;
			}
		}
		return false;
	}

	/**
	 * @param data
	 *            string containing url and title separated by <quote>\n</quote>
	 * @return true if task succesfully created, false otherwise
	 */
	public boolean createTaskFromUrl(Object data) {
		if (!(data instanceof String)) {
			return false;
		}

		String[] urlTransfer = ((String) data).split("\n");

		String url = "";
		String urlTitle = "<retrieving from URL>";

		if (urlTransfer.length > 0) {
			url = urlTransfer[0];
		} else {
			return false;
		}

		AbstractRepositoryConnector connector = TasksUiPlugin.getRepositoryManager().getConnectorForRepositoryTaskUrl(
				url);
		if (connector != null) {
			String repositoryUrl = connector.getRepositoryUrlFromTaskUrl(url);
			String id = connector.getTaskIdFromTaskUrl(url);
			if (repositoryUrl == null || id == null) {
				return false;
			}
			for (TaskRepository repository : TasksUi.getRepositoryManager().getRepositories(
					connector.getConnectorKind())) {
				if (repository.getRepositoryUrl().equals(repositoryUrl)) {
					try {
						newTask = (AbstractTask) TasksUiInternal.createTask(repository, id, new NullProgressMonitor());
						TasksUiInternal.refreshAndOpenTaskListElement(newTask);
						return true;
					} catch (CoreException e) {
						StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Could not create task", e));
						return false;
					}
				}
			}
			return false;
		} else {
			// Removed in order to default to retrieving title from url rather
			// than
			// accepting what was sent by the brower's DnD code. (see bug
			// 114401)
			// If a Title is provided, use it.
			// if (urlTransfer.length > 1) {
			// urlTitle = urlTransfer[1];
			// }
			// if (urlTransfer.length < 2) { // no title provided
			// retrieveTaskDescription(url);
			// }
			retrieveTaskDescription(url);

			newTask = TasksUiInternal.createNewLocalTask(urlTitle);
			if (newTask == null) {
				return false;
			}
			newTask.setUrl(url);
			TasksUiUtil.openTask(newTask);
			return true;
		}
	}

	public boolean createTaskFromString(String title) {
		//newTask = new Task(TasksUiPlugin.getTaskListManager().genUniqueTaskHandle(), title);
		newTask = TasksUiInternal.createNewLocalTask(title);

		if (newTask == null) {
			return false;
		} else {
			//newTask.setPriority(Task.PriorityLevel.P3.toString());
			TasksUiUtil.openTask(newTask);
			return true;
		}
	}

	@Override
	public boolean validateDrop(Object targetObject, int operation, TransferData transferType) {
		currentTransfer = transferType;

		if (FileTransfer.getInstance().isSupportedType(currentTransfer)) {
			// handle all files
			return true;
		} else if (TaskTransfer.getInstance().isSupportedType(currentTransfer)) {
			if (getCurrentTarget() instanceof UncategorizedTaskContainer || getCurrentTarget() instanceof TaskCategory
					|| getCurrentTarget() instanceof UnmatchedTaskContainer
					|| getCurrentTarget() instanceof ScheduledTaskContainer) {
				return true;
			} else if (getCurrentTarget() instanceof ITaskContainer
					&& (getCurrentLocation() == ViewerDropAdapter.LOCATION_AFTER || getCurrentLocation() == ViewerDropAdapter.LOCATION_BEFORE)) {
				return true;
			} else if (getCurrentTarget() instanceof LocalTask
					&& getCurrentLocation() == ViewerDropAdapter.LOCATION_ON
					&& TasksUiPlugin.getDefault().getPreferenceStore().getBoolean(
							ITasksUiPreferenceConstants.LOCAL_SUB_TASKS_ENABLED)) {
				return true;
			} else {
				return false;
			}
		}

		return TextTransfer.getInstance().isSupportedType(transferType);
	}

	/**
	 * Attempts to set the task pageTitle to the title from the specified url
	 */
	protected void retrieveTaskDescription(final String url) {
		try {
			AbstractRetrieveTitleFromUrlJob job = new AbstractRetrieveTitleFromUrlJob(url) {
				@Override
				protected void titleRetrieved(final String pageTitle) {
					newTask.setSummary(pageTitle);
					TasksUiInternal.getTaskList().notifyElementChanged(newTask);
				}
			};
			job.schedule();
		} catch (RuntimeException e) {
			// FIXME what exception is caught here?
			StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Could not open task web page", e));
		}
	}
}

Back to the top