public class AngularProject implements IDirectiveSyntax, ITernProjectLifecycleListener {

	private static final String ANGULAR_PROJECT = AngularProject.class.getName();

	public static final String DEFAULT_START_SYMBOL = "{{";
	public static final String DEFAULT_END_SYMBOL = "}}";

	private final IIDETernProject ternProject;
	private String startSymbol;
	private String endSymbol;

	private final Map<ITernScriptPath, List<BaseModel>> folders;

	private final CustomAngularModulesRegistry customDirectives;

	private AngularOutlineProvider outlineProvider;

	AngularProject(IIDETernProject ternProject) throws CoreException {
		this.ternProject = ternProject;
		this.outlineProvider = new AngularOutlineProvider(ternProject);
		this.folders = new HashMap<ITernScriptPath, List<BaseModel>>();
		this.customDirectives = new CustomAngularModulesRegistry(ternProject.getProject());
		AngularModulesManager.getInstance().addRegistry(this, customDirectives);
		ternProject.setData(ANGULAR_PROJECT, this);
		ternProject.addServerListener(new TernServerAdapter() {
			@Override
			public void onStop(ITernServer server) {
				customDirectives.clear();
			}
		});
		// initialize symbols from project preferences
		initializeSymbols();
		AngularCorePreferencesSupport.getInstance().getEclipsePreferences(ternProject.getProject())
				.addPreferenceChangeListener(new IPreferenceChangeListener() {

					@Override
					public void preferenceChange(PreferenceChangeEvent event) {
						if (AngularCoreConstants.EXPRESSION_START_SYMBOL.equals(event.getKey())) {
							AngularProject.this.startSymbol = event.getNewValue().toString();
						} else if (AngularCoreConstants.EXPRESSION_END_SYMBOL.equals(event.getKey())) {
							AngularProject.this.endSymbol = event.getNewValue().toString();
						}
					}
				});
	}

	/**
	 * Initialize start/end symbols.
	 */
	private void initializeSymbols() {
		this.startSymbol = AngularCorePreferencesSupport.getInstance().getStartSymbol(getProject());
		this.endSymbol = AngularCorePreferencesSupport.getInstance().getEndSymbol(getProject());
	}

	public static AngularProject getAngularProject(IProject project) throws CoreException {
		if (!hasAngularNature(project)) {
			throw new CoreException(new Status(IStatus.ERROR, AngularCorePlugin.PLUGIN_ID,
					"The project " + project.getName() + " is not an angular project."));
		}
		IIDETernProject ternProject = TernCorePlugin.getTernProject(project);
		AngularProject angularProject = ternProject.getData(ANGULAR_PROJECT);
		if (angularProject == null) {
			angularProject = new AngularProject(ternProject);
		}
		return angularProject;
	}

	public IProject getProject() {
		return ternProject.getProject();
	}

	public static IIDETernProject getTernProject(IProject project) throws CoreException {
		return TernCorePlugin.getTernProject(project);
	}

	/**
	 * Return true if the given project have angular nature and false otherwise.
	 * 
	 * @param project
	 *            Eclipse project.
	 * @return true if the given project have angular nature and false
	 *         otherwise.
	 */
	public static boolean hasAngularNature(IProject project) {
		if (project.isAccessible()) {
			try {
				if (TernCorePlugin.hasTernNature(project)) {
					IIDETernProject ternProject = TernCorePlugin.getTernProject(project);
					if (ternProject.hasPlugin(TernPlugin.angular1)) {
						return true;
					}
					if (ternProject.hasPlugin("angular")) {
						try {
							// .tern-project must be updated with angular1
							ITernModule angular = ternProject.getRepository().getModule("angular");
							JsonValue options = (angular instanceof ITernModuleConfigurable)
									? ((ITernModuleConfigurable) angular).getOptions() : null;
							ternProject.addPlugin(TernPlugin.angular1, options);
							ternProject.getPlugins().remove("angular");
							ternProject.save();
						} catch (Exception e) {
							Trace.trace(Trace.SEVERE, "Error while updating .tern-project with angular1", e);
							return false;
						}
						AngularCorePlugin.getDefault().getLog().log(new Status(IStatus.INFO,
								AngularCorePlugin.PLUGIN_ID, ".tern-project was updated with angular1"));
						return true;
					}
				}
			} catch (CoreException e) {
				Trace.trace(Trace.SEVERE, "Error angular nature", e);
			}
		}
		return false;
	}

	public Collection<BaseModel> getFolders(ITernScriptPath scriptPath) {
		List<BaseModel> folders = this.folders.get(scriptPath);
		if (folders == null) {
			folders = new ArrayList<BaseModel>();
			this.folders.put(scriptPath, folders);
			folders.add(new ScriptsFolder(scriptPath));
			folders.add(new ModulesFolder(scriptPath));
		}
		return folders;
	}

	public void cleanModel() {
		this.folders.clear();
	}

	public Directive getDirective(String tagName, String name, Restriction restriction) {
		return AngularModulesManager.getInstance().getDirective(this, tagName, name, restriction);
	}

	public void collectDirectives(String tagName, String directiveName, List<Directive> existingDirectives,
			Restriction restriction, IDirectiveCollector collector) {
		AngularModulesManager.getInstance().collectDirectives(this, tagName, directiveName, this, existingDirectives,
				restriction, collector);

	}

	@Override
	public boolean isUseOriginalName() {
		return AngularCorePreferencesSupport.getInstance().isDirectiveUseOriginalName(getProject());
	}

	@Override
	public boolean isStartsWithNothing() {
		return AngularCorePreferencesSupport.getInstance().isDirectiveStartsWithNothing(getProject());
	}

	@Override
	public boolean isStartsWithX() {
		return AngularCorePreferencesSupport.getInstance().isDirectiveStartsWithX(getProject());
	}

	@Override
	public boolean isStartsWithData() {
		return AngularCorePreferencesSupport.getInstance().isDirectiveStartsWithData(getProject());
	}

	@Override
	public boolean isColonDelimiter() {
		return AngularCorePreferencesSupport.getInstance().isDirectiveColonDelimiter(getProject());
	}

	@Override
	public boolean isMinusDelimiter() {
		return AngularCorePreferencesSupport.getInstance().isDirectiveMinusDelimiter(getProject());
	}

	@Override
	public boolean isUnderscoreDelimiter() {
		return AngularCorePreferencesSupport.getInstance().isDirectiveUnderscoreDelimiter(getProject());
	}

	/**
	 * Returns the start symbol used inside HTML for angular expression.
	 * 
	 * @return the start symbol used inside HTML for angular expression.
	 */
	public String getStartSymbol() {
		return startSymbol;
	}

	/**
	 * Returns the end symbol used inside HTML for angular expression.
	 * 
	 * @return the end symbol used inside HTML for angular expression.
	 */
	public String getEndSymbol() {
		return endSymbol;
	}

	@Override
	public void handleEvent(IIDETernProject project, LifecycleEventType state) {
		switch (state) {
		case onDisposeAfter:
			dispose();
		default:
		}
	}

	private void dispose() {
		customDirectives.dispose();
	}

	/**
	 * Returns the angular outline provider which hosts modules, controllers,
	 * directives of the angular project.
	 * 
	 * @return the angular outline provider which hosts modules, controllers,
	 *         directives of the angular project.
	 * @throws IOException
	 * @throws TernException
	 */
	public AngularOutlineProvider getOutlineProvider() throws IOException, TernException {
		outlineProvider.init();
		return outlineProvider;
	}
	
	public AngularOutlineProvider getOutlineProvider(ITernFile ternFile) throws IOException, TernException {
		outlineProvider.refresh(ternFile);
		return outlineProvider;
	}

	public void addAngularOutlineListener(IAngularOutlineListener listener) {
		outlineProvider.addAngularOutlineListener(listener);
	}

	public void removeAngularOutlineListener(IAngularOutlineListener listener) {
		outlineProvider.removeAngularOutlineListener(listener);
	}

} public class AngularLinkHelper {

	static final QualifiedName CONTROLLER_INFO = new QualifiedName(
			TernCorePlugin.PLUGIN_ID + ".resourceprops", "ControllerInfo");

	public static void setController(String module,
			String controller, IResource resource, String elementId)
			throws Exception {
		AngularLinkResource linkResource = getControllerInfo(resource);
		if (linkResource == null) {
			linkResource = new AngularLinkResource(resource, null);
		}
		linkResource.addLink(module, controller, elementId);
		linkResource.save();
	}

	public static AngularLinkResource getControllerInfo(IResource resource)
			throws Exception {
		AngularLinkResource info = (AngularLinkResource) resource
				.getSessionProperty(CONTROLLER_INFO);
		if (info == null) {
			String resourceInfo = resource
					.getPersistentProperty(CONTROLLER_INFO);
			if (!StringUtils.isEmpty(resourceInfo)) {
				info = new AngularLinkResource(resource, resourceInfo);
				info.save();
			}
		}
		return info;
	}

	public static void removeController(IResource resource,
			ITernScriptPath scriptPath, String module, String controller,
			String elementId) throws CoreException {
		resource.setSessionProperty(CONTROLLER_INFO, null);
		resource.setPersistentProperty(CONTROLLER_INFO, null);
	}

	public static boolean hasController(IResource resource) {
		try {
			return getControllerInfo(resource) != null;
		} catch (Exception e) {
			return false;
		}
	}

	public static boolean isSameController(IResource resource,
			String module, String controller,
			String elementId) {
		try {
			AngularLinkResource info = getControllerInfo(resource);
			if (info != null) {
				if (elementId != null) {
					if (info.getElementLinks() != null) {
						for (AngularLink elementLink : info.getElementLinks()) {
							if (isSameController(elementLink, 
									module, controller, elementId)) {
								return true;
							}
						}
					}
				}
				if (info.getResourceLink() != null) {
					return isSameController(info.getResourceLink(), 
							module, controller, elementId);
				}
			}
			return false;
		} catch (Exception e) {
			return false;
		}
	}

	private static boolean isSameController(AngularLink link,
			 String module, String controller,
			String elementId) {
		if (!link.getModule().equals(module)) {
			// not the same module
			return false;
		}
		if (!StringUtils.isEmpty(link.getController())) {
			if (!link.getController().equals(controller)) {
				// not the same controller
				return false;
			}
		} else {
			if (controller != null) {
				return false;
			}
		}
		if (!StringUtils.isEmpty(link.getElementId())) {
			if (!link.getElementId().equals(elementId)) {
				// not the same elementId
				return false;
			}
		} else {
			if (elementId != null) {
				return false;
			}
		}
		return true;

	}

}
 public final class AngularUIMessages extends NLS {

	private static final String BUNDLE_NAME = "org.eclipse.angularjs.internal.ui.AngularUIMessages"; //$NON-NLS-1$

	private static ResourceBundle fResourceBundle;

	public static String ConvertProjectToAngular_converting_project_job_title;

	public static String AngularGlobalPreferencesPage_desc;
	public static String HTMLAngularGlobalPreferencesPage_desc;
	public static String HTMLAngularEditorPreferencesPage_desc;

	public static String Sample_HTMLAngular_doc;

	public static String AngularTyping_Auto_Complete;
	public static String AngularTyping_Close_EL;

	// Angular Explorer View
	public static String AngularOutline_computing;
	
	public static String GoToDefinitionAction_text;
	public static String GoToDefinitionAction_tooltip;
	public static String LinkToControllerAction_text;
	public static String LinkToControllerAction_tooltip;
	public static String RefreshExplorerAction_text;
	public static String RefreshExplorerAction_tooltip;
	public static String UnLinkToControllerAction_text;
	public static String UnLinkToControllerAction_tooltip;

	public static String AngularExplorerView_openFile_error;
	public static String AngularExplorerView_openFileDialog_title;

	public static String LexicalSortingAction_text;
	public static String LexicalSortingAction_tooltip;
	public static String LexicalSortingAction_description;

	// Hyperlink
	public static String HTMLAngularHyperLink_text;
	public static String HTMLAngularHyperLink_typeLabel;

	// Preferences
	public static String DirectivesPropertyPage_desc;
	public static String DirectivesPropertyPage_useOriginalName_label;
	public static String DirectivesPropertyPage_startsWithLabel_text;
	public static String DirectivesPropertyPage_startsWithNothing_label;
	public static String DirectivesPropertyPage_startsWithX_label;
	public static String DirectivesPropertyPage_startsWithData_label;
	public static String DirectivesPropertyPage_delimiterLabel_text;
	public static String DirectivesPropertyPage_colonDelimiter_label;
	public static String DirectivesPropertyPage_minusDelimiter_label;
	public static String DirectivesPropertyPage_underscoreDelimiter_label;
	public static String DirectivesPropertyPage_directiveTestLabel_text;

	public static String ExpressionPropertyPage_startSybol_label;
	public static String ExpressionPropertyPage_endSybol_label;

	public static String OpenAngularElementAction_label;
	public static String OpenAngularElementAction_description;
	public static String OpenAngularElementAction_tooltip;
	public static String OpenAngularElementAction_dialogMessage;
	public static String OpenAngularElementAction_dialogTitle;

	// Protractor
	public static String ProtractorLaunchShortcut_Error;
	public static String ProtractorLaunchShortcut_Protractor_Failed;

	public static String ProtractorPreferencesPage_desc;
	public static String ProtractorPreferencesPage_defaultCliFile_label;
	public static String ProtractorPreferencesPage_debugger_label;
	
	public static String Protractor_MainTab_location_label;
	public static String Protractor_MainTab_Select_a_protractor_config_file;
	public static String Protractor_ProtractorTab_name;
	public static String Protractor_ProtractorTab_cliFile;


	private AngularUIMessages() {
	}

	public static ResourceBundle getResourceBundle() {
		try {
			if (fResourceBundle == null)
				fResourceBundle = ResourceBundle.getBundle(BUNDLE_NAME);
		} catch (MissingResourceException x) {
			fResourceBundle = null;
		}
		return fResourceBundle;
	}

	static {
		NLS.initializeMessages(BUNDLE_NAME, AngularUIMessages.class);
	}
} public class AngularUIPlugin extends AbstractUIPlugin {

	// The plug-in ID
	public static final String PLUGIN_ID = "org.eclipse.angularjs.ui"; //$NON-NLS-1$

	// The shared instance
	private static AngularUIPlugin plugin;

	/**
	 * The constructor
	 */
	public AngularUIPlugin() {
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
	 * )
	 */
	public void start(BundleContext context) throws Exception {
		super.start(context);
		plugin = this;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
	 * )
	 */
	public void stop(BundleContext context) throws Exception {
		plugin = null;
		super.stop(context);
	}

	/**
	 * Returns the shared instance
	 * 
	 * @return the shared instance
	 */
	public static AngularUIPlugin getDefault() {
		return plugin;
	}

	public static IWorkbenchWindow getActiveWorkbenchWindow() {
		return getDefault().getWorkbench().getActiveWorkbenchWindow();
	}

	public static Shell getActiveWorkbenchShell() {
		IWorkbenchWindow window = getActiveWorkbenchWindow();
		if (window != null) {
			return window.getShell();
		}
		return null;
	}

	/**
	 * @return Returns the active workbench window's currrent page.
	 */
	public static IWorkbenchPage getActivePage() {
		return getActiveWorkbenchWindow().getActivePage();
	}

}
 public class AngularExplorerContentProvider extends
		TernScriptPathContentProvider {

	@Override
	public Object[] getChildren(Object element) {
		if (element instanceof ITernScriptPath) {
			ITernScriptPath scriptPath = (ITernScriptPath) element;
			try {
				AngularProject angularProject = AngularProject
						.getAngularProject((IProject) scriptPath.getOwnerProject().
								getAdapter(IProject.class));
				return angularProject.getFolders(scriptPath).toArray();
			} catch (CoreException e) {
				e.printStackTrace();
			}
		}
		if (element instanceof BaseModel) {
			switch (((BaseModel) element).getType()) {
			case ScriptsFolder:
				return ((ScriptsFolder) element).getScriptPath()
						.getScriptResources().toArray();
			case ModulesFolder:
				return ((ModulesFolder) element).getModules();
			case Module:
				return ((Module) element).getAngularElements();
			}
		}
		return null;
	}

	@Override
	public boolean hasChildren(Object element) {
		if (super.hasChildren(element)) {
			return true;
		}
		if (element instanceof BaseModel) {
			return !((BaseModel) element).getType().equals(
					BaseModel.Type.AngularElement);
		}
		return false;
	}

} public class AngularExplorerLabelProvider extends TernScriptPathLabelProvider {

	private final AngularExplorerViewOLD view;

	public AngularExplorerLabelProvider(AngularExplorerViewOLD view) {
		this.view = view;
	}

	@Override
	public String getText(Object element) {
		if (element instanceof BaseModel) {
			return ((BaseModel) element).getName();
		}
		return super.getText(element);
	}

	@Override
	public Image getImage(Object element) {
		if (element instanceof BaseModel) {
			IResource resource = view.getCurrentResource();
			switch (((BaseModel) element).getType()) {
			case Module:
				Module module = (Module) element;
				return ImageResource.getImage(ImageResource.IMG_ANGULARJS);
			case AngularElement:
				AngularElement angularElement = (AngularElement) element;
				switch (angularElement.getAngularType()) {
				case controller:
					return ImageResource.getImage(ImageResource.IMG_CONTROLLER);
				case directive:
					return ImageResource.getImage(ImageResource.IMG_DIRECTIVE);
				case filter:
					return ImageResource.getImage(ImageResource.IMG_FILTER);
				case factory:
					return ImageResource.getImage(ImageResource.IMG_FACTORY);
				case provider:
					return ImageResource.getImage(ImageResource.IMG_PROVIDER);
				case service:
					return ImageResource.getImage(ImageResource.IMG_SERVICE);
				}

			default:
				return ImageResource.getImage(ImageResource.IMG_FOLDER);
			}
		}
		return super.getImage(element);
	}
}
 public class GoToDefinitionAction extends Action {

	private final AngularExplorerViewOLD explorer;

	public GoToDefinitionAction(AngularExplorerViewOLD explorer) {
		this.explorer = explorer;
		super.setText(AngularUIMessages.GoToDefinitionAction_text);
		super.setToolTipText(AngularUIMessages.GoToDefinitionAction_tooltip);
		super.setImageDescriptor(ImageResource
				.getImageDescriptor(ImageResource.IMG_ELCL_GOTO_DEF));
	}

	@Override
	public void run() {
		IStructuredSelection selection = (IStructuredSelection) explorer
				.getViewer().getSelection();
		if (!selection.isEmpty()) {
			Object firstSelection = selection.getFirstElement();
			explorer.tryOpenInEditor(firstSelection);
		}
	}
}
 public class LexicalSortingAction extends Action {
	private final AngularExplorerViewOLD explorer;
	private LexicalSorter sorter;

	public LexicalSortingAction(AngularExplorerViewOLD explorer) {
		super(AngularUIMessages.LexicalSortingAction_text, SWT.TOGGLE);
		this.explorer = explorer;
		this.sorter = new LexicalSorter();
		super.setToolTipText(AngularUIMessages.LexicalSortingAction_tooltip);
		super.setDescription(AngularUIMessages.LexicalSortingAction_description);

		boolean checked= AngularUIPlugin.getDefault().getPreferenceStore()
				.getBoolean("LexicalSortingAction.isChecked");
		valueChanged(checked, false);
	}

	@Override
	public void run() {
		valueChanged(isChecked(), true);
	}

	private void valueChanged(final boolean on, boolean store) {
		setChecked(on);
		BusyIndicator.showWhile(explorer.getViewer().getControl().getDisplay(), new Runnable() {
			@Override
			public void run() {
				if (on) {
					explorer.getViewer().setSorter(sorter);
				} else {
					explorer.getViewer().setSorter(null);
				}
			}
		});

		if (store) {
			AngularUIPlugin.getDefault().getPreferenceStore()
				.setValue("LexicalSortingAction.isChecked", on);
		}
	}

	class LexicalSorter extends ViewerSorter {
		@Override
		public int category(Object element) {
			if (element instanceof BaseModel) {
				switch (((BaseModel) element).getType()) {
				case Module:
				case ScriptsFolder:
					return 0;
				case AngularElement:
					AngularElement angularElement = (AngularElement) element;
					switch (angularElement.getAngularType()) {
					case controller:
						return 5;
					case directive:
						return 6;
					case filter:
						return 7;
					case factory:
						return 8;
					case provider:
						return 9;
					case service:
						return 10;
					default:
						return 11;
					}
				default:
					return 1;
				}
			}
			return 12;
		}
	}
} public class LinkToControllerAction extends Action {

	private final AngularExplorerViewOLD explorer;

	public LinkToControllerAction(AngularExplorerViewOLD explorer) {
		this.explorer = explorer;
		super.setText(AngularUIMessages.LinkToControllerAction_text);
		super.setToolTipText(AngularUIMessages.LinkToControllerAction_tooltip);
		super.setImageDescriptor(ImageResource
				.getImageDescriptor(ImageResource.IMG_ELCL_LINK_TO_CTRL));
	}

	@Override
	public void run() {
		IResource resource = explorer.getCurrentResource();
		if (resource != null) {
			IStructuredSelection selection = (IStructuredSelection) explorer
					.getViewer().getSelection();
			if (!selection.isEmpty()) {
				Module module = null;
				AngularElement angularElement = null;
				String elementId = null;
				Object firstSelection = selection.getFirstElement();
				if (firstSelection instanceof Module) {
					module = (Module) firstSelection;
				} else if (firstSelection instanceof AngularElement) {
					angularElement = (AngularElement) firstSelection;
					module = angularElement.getModule();
				}
				if (module != null) {
					try {
						AngularLinkHelper.setController(
								module.getName(),
								angularElement != null ? angularElement.getName()
										: null, resource, elementId);
						explorer.updateEnabledLinkActions(true);
						explorer.refreshTree(true);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
} public class RefreshExplorerAction extends Action {

	private final AngularExplorerViewOLD explorer;

	public RefreshExplorerAction(AngularExplorerViewOLD explorer) {
		this.explorer = explorer;
		super.setText(AngularUIMessages.RefreshExplorerAction_text);
		super.setToolTipText(AngularUIMessages.RefreshExplorerAction_tooltip);
		super.setImageDescriptor(ImageResource
				.getImageDescriptor(ImageResource.IMG_ELCL_REFRESH));
	}

	@Override
	public void run() {
		explorer.refreshTree(false);
	}

}
 public class UnLinkToControllerAction extends Action {

	private final AngularExplorerViewOLD explorer;

	public UnLinkToControllerAction(AngularExplorerViewOLD explorer) {
		this.explorer = explorer;
		super.setText(AngularUIMessages.UnLinkToControllerAction_text);
		super.setToolTipText(AngularUIMessages.UnLinkToControllerAction_tooltip);
		super.setImageDescriptor(ImageResource
				.getImageDescriptor(ImageResource.IMG_ELCL_UNLINK_TO_CTRL));
	}

	@Override
	public void run() {
		IResource resource = explorer.getCurrentResource();
		if (resource != null) {
			IStructuredSelection selection = (IStructuredSelection) explorer
					.getViewer().getSelection();
			if (!selection.isEmpty()) {
				Object firstSelection = selection.getFirstElement();

				Module module = null;
				AngularElement controller = null;
				String elementId = null;
				if (firstSelection instanceof Module) {
					module = (Module) firstSelection;
				} else if (firstSelection instanceof AngularElement) {
					controller = (AngularElement) firstSelection;
					module = controller.getModule();
				}
				if (module != null) {
					try {
						AngularLinkHelper.removeController(resource, module
								.getScriptPath(), module.getName(),
								controller != null ? controller.getName()
										: null, elementId);
						explorer.updateEnabledLinkActions(true);
						explorer.refreshTree(true);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}
import java.util.Collections;
import org.eclipse.angularjs.core.AngularElement;
import org.eclipse.angularjs.core.AngularProject;
import org.eclipse.angularjs.core.IDefinitionAware;
import org.eclipse.angularjs.core.Module;
import org.eclipse.angularjs.core.link.AngularLinkHelper;
import org.eclipse.angularjs.internal.ui.AngularUIMessages;
import org.eclipse.angularjs.internal.ui.AngularUIPlugin;
import org.eclipse.angularjs.internal.ui.viewers.AngularExplorerContentProvider;
import org.eclipse.angularjs.internal.ui.viewers.AngularExplorerLabelProvider;
import org.eclipse.angularjs.internal.ui.views.actionsOLD.GoToDefinitionAction;
import org.eclipse.angularjs.internal.ui.views.actionsOLD.LexicalSortingAction;
import org.eclipse.angularjs.internal.ui.views.actionsOLD.LinkToControllerAction;
import org.eclipse.angularjs.internal.ui.views.actionsOLD.RefreshExplorerAction;
import org.eclipse.angularjs.internal.ui.views.actionsOLD.UnLinkToControllerAction;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IPartListener2;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchPartReference;
import org.eclipse.ui.part.ViewPart;
import tern.ITernFile;
import tern.angular.AngularType;
import tern.angular.protocol.outline.AngularOutline;
import tern.eclipse.ide.core.IIDETernProject;
import tern.eclipse.ide.core.ITernProjectLifecycleListener;
import tern.eclipse.ide.core.TernCorePlugin;
import tern.eclipse.ide.ui.utils.EditorUtils;
import tern.scriptpath.ITernScriptPath;
import tern.scriptpath.ITernScriptResource;
import tern.server.ITernServer;
import tern.server.ITernServerListener;
import tern.server.protocol.IJSONObjectHelper;
import tern.server.protocol.definition.ITernDefinitionCollector;
import tern.server.protocol.push.IMessageHandler;
/**
 *  Copyright (c) 2013-2014 Angelo ZERR.
 *  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:
 *  Angelo Zerr <angelo.zerr@gmail.com> - initial API and implementation
 */
package org.eclipse.angularjs.internal.ui.views;




/**
 * Angular explorer view.
 * 
 */
public class AngularExplorerViewOLD extends ViewPart implements
		ISelectionListener, ITernDefinitionCollector, ITernServerListener,
		ITernProjectLifecycleListener, IMessageHandler {

	private IWorkbenchPart currentEditor;
	private IIDETernProject currentTernProject;
	private IResource currentResource;
	private TreeViewer viewer;

	private LinkToControllerAction linkAction;
	private UnLinkToControllerAction unLinkAction;
	private GoToDefinitionAction openAction;
	private RefreshExplorerAction refreshAction;
	private LexicalSortingAction sortAction;

	private IPartListener2 partListener = new IPartListener2() {
		public void partVisible(IWorkbenchPartReference ref) {
			if (ref.getId().equals(getSite().getId())) {
				IWorkbenchPart activePart = ref.getPage().getActivePart();
				if (activePart != null)
					selectionChanged(activePart, ref.getPage().getSelection());
				startListeningForSelectionChanges();
			}
		}

		public void partHidden(IWorkbenchPartReference ref) {
			if (ref.getId().equals(getSite().getId()))
				stopListeningForSelectionChanges();
		}

		public void partInputChanged(IWorkbenchPartReference ref) {

		}

		public void partActivated(IWorkbenchPartReference ref) {
		}

		public void partBroughtToTop(IWorkbenchPartReference ref) {
		}

		public void partClosed(IWorkbenchPartReference ref) {
		}

		public void partDeactivated(IWorkbenchPartReference ref) {
		}

		public void partOpened(IWorkbenchPartReference ref) {
		}
	};

	@Override
	public void createPartControl(Composite parent) {
		FillLayout layout = new FillLayout();
		parent.setLayout(layout);

		viewer = new TreeViewer(parent, SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI);
		viewer.setContentProvider(new AngularExplorerContentProvider());
		viewer.setLabelProvider(new AngularExplorerLabelProvider(this));
		viewer.addSelectionChangedListener(new ISelectionChangedListener() {

			@Override
			public void selectionChanged(SelectionChangedEvent event) {
				updateEnabledActions();
			}

		});

		Tree tree = viewer.getTree();
		tree.setHeaderVisible(false);
		tree.setLinesVisible(false);
		tree.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseDoubleClick(MouseEvent e) {
				Tree tree = (Tree) e.getSource();
				if (tree.getSelectionCount() > 0) {
					Object firstSelection = tree.getSelection()[0].getData();
					tryOpenInEditor(firstSelection);
				}
			}
		});

		registerActions();
		registerContextMenu();

		getSite().getWorkbenchWindow().getPartService()
				.addPartListener(partListener);
		TernCorePlugin.addTernProjectLifeCycleListener(this);
		updateEnabledActions();
	}

	/**
	 * Update enabled of actions.
	 */
	private void updateEnabledActions() {
		this.linkAction.setEnabled(false);
		this.unLinkAction.setEnabled(false);
		this.openAction.setEnabled(false);
		IStructuredSelection selection = (IStructuredSelection) viewer
				.getSelection();
		if (!selection.isEmpty()) {
			Object firstSelection = selection.getFirstElement();
			// Open action (Go To Definition available if teh selected element
			// can be opened in a editor).
			this.openAction
					.setEnabled(firstSelection instanceof ITernScriptResource
							|| firstSelection instanceof IDefinitionAware);
			// Link/Unlink actions
			Module module = null;
			AngularElement controller = null;
			String elementId = null;
			if (firstSelection instanceof Module) {
				// The selected element is a module.
				module = (Module) firstSelection;
			} else if (firstSelection instanceof AngularElement
					&& AngularType.controller == ((AngularElement) firstSelection)
							.getAngularType()) {
				// The selected element is a controller.
				controller = (AngularElement) firstSelection;
				module = controller.getModule();
			}
			IResource resource = getCurrentResource();
			if (resource != null && module != null) {
				boolean isLinked = AngularLinkHelper.isSameController(resource,